/* jshint node:true */
'use strict';

var events = require('events');
var util = require('util');
var extend = require('util')._extend

var request = require('request');
var xml2js = require('xml2js');

function Sender() {
  var self = this;

  events.EventEmitter.call(self);

  self.device = null;
  self.appID = null;
  self.appURL = null;

  self.token = null;
  self.state = null;
}

util.inherits(Sender, events.EventEmitter);

Sender.prototype.launchApp = function (cb) {
  var self = this;

  var uri = util.format('%s/%s', self.device.applicationUrl, self.appID);
  var body = {
    type: 'launch', // launch, relaunch, join
    app_info: {
      url: self.appURL,
      useIpc: false, // needs WebSocket channel
      maxInactive: -1 // when useIpc is false, receiver running time in ms, -1 is forever
    }
  };
  request({uri: uri, method: 'POST', body: body, json: true}, function (err, res, body) {
    self.token = body.token;
    // TODO: handle body.interval, the heartbeat interval

    // NB: res.statusCode === 201 launched by request, === 200 already running

    cb(err);
  });
};

Sender.prototype.getState = function (cb) {
  var self = this;

  var uri = util.format('%s/%s', self.device.applicationUrl, self.appID);
  var headers = {
    'Accept': 'application/xml; charset=utf8'
  };
  if (self.token) {
    extend(headers, {'Authorization': self.token});
  }
  request({uri: uri, method: 'GET', headers: headers}, function (err, res, body) {
    var parser = new xml2js.Parser();
    parser.parseString(body, function (err, result) {
//      console.log(util.inspect(body));
//      console.log(util.inspect(result));
      var state = result.service.state[0];
      if (state === 'starting' || state === 'running' || state === 'stopped') {
        self.state = state;
      }

      cb(err, self.state);
    });
  });
};

Sender.prototype.closeApp = function (cb) {
  var self = this;

  var uri = util.format('%s/%s/run', self.device.applicationUrl, self.appID);
  var headers = {
    'Accept': 'application/xml; charset=utf8',
    'Authorization': self.token
  };
  request({uri: uri, method: 'DELETE', headers: headers}, function (err, res, body) {
    cb(err);
  });
};

module.exports = Sender;

@@ -2197,16 +2197,966 @@
 %7D);%0A%7D;%0A%0A
+Sender.prototype.systemControl = function (type, value, cb) %7B%0A  var self = this%0A%0A  if (typeof value === 'function') %7B%0A    cb = value;%0A  %7D%0A%0A  // really odd REST semantics https://github.com/openflint/flingd-coffee/issues/2%0A  var uri = util.format('%25s/system/control', self.device.applicationUrl.replace(/%5C/apps$/, ''));%0A  var body = %7B%0A    type: type%0A  %7D;%0A  if (type === 'SET_VOLUME') %7B%0A    extend(body, %7Blevel: value%7D);%0A  %7D else if (type === 'SET_MUTED') %7B%0A    extend(body, %7Bmuted: value%7D);%0A  %7D%0A  request(%7Buri: uri, method: 'POST', body: body, json: true%7D, function (err, res, body) %7B%0A    // only the GET_* requests return content https://github.com/openflint/flingd-coffee/issues/1%0A    var result = undefined;%0A    if (body && body.success) %7B%0A      if (body.request_type === 'GET_VOLUME') %7B%0A          result = body.level;%0A      %7D else if (body.request_type === 'GET_MUTED') %7B%0A        result = body.muted;%0A      %7D%0A    %7D%0A%0A    cb(err, result);%0A  %7D);%0A%7D;%0A%0A
 module.e

add basic system control support