var SERVER = 'http://127.0.0.1:8888';

var KEY_TIME    = 0;
var KEY_COMMAND = 1;
var KEY_SCREEN  = 2;

function httpGet(url) {
  var xhr = new XMLHttpRequest();
  xhr.open('GET', url, true);
  xhr.onerror = function() {
    console.log('[SuM] request failed: ' + url);
  };
  xhr.send();
}

function sendScreenToWatch() {
  var xhr = new XMLHttpRequest();
  xhr.open('GET', SERVER + '/screen', true);
  xhr.onload = function() {
    if (xhr.status === 200) {
      try {
        var data = JSON.parse(xhr.responseText);
        var msg = {};
        msg[KEY_SCREEN] = data.text;
        Pebble.sendAppMessage(
          msg,
          function() {},
          function(e) { console.log('[SuM] sendAppMessage failed: ' + JSON.stringify(e)); }
        );
      } catch (err) {
        console.log('[SuM] JSON parse error: ' + err);
      }
    }
  };
  xhr.onerror = function() {
    console.log('[SuM] GET /screen failed - is the companion app running?');
  };
  xhr.send();
}

Pebble.addEventListener('ready', function() {
  setInterval(sendScreenToWatch, 1000);
});

Pebble.addEventListener('appmessage', function(e) {
  var command = e.payload[KEY_COMMAND];
  if (!command) { return; }
  httpGet(SERVER + '/key?cmd=' + encodeURIComponent(command));
});
