/* jshint esversion: 6 */

// battle API mode flags
const FLAGS = [
  { "mask": 1, "attr": "See others" },
  { "mask": 2, "attr": "See times" },
  { "mask": 4, "attr": "Allow starter" },
  { "mask": 8, "attr": "Apple bug" },
  { "mask": 16, "attr": "No volt" },
  { "mask": 32, "attr": "No turn" },
  { "mask": 64, "attr": "One turn" },
  { "mask": 128, "attr": "No brake" },
  { "mask": 256, "attr": "No throttle" },
  { "mask": 512, "attr": "Always throttle" },
  { "mask": 1024, "attr": "Drunk" },
  { "mask": 4096, "attr": "One wheel" },
  { "mask": 8192, "attr": "Multi" }
];

// battle API battle type
const TYPES = [
  "Normal", "One life", "First finish", "Slowness", "Survivor", "Last result", "Finish count", "1 Hour TT", "Flag tag", "Apple", "Speed"
];

var APIurl = "http://108.61.164.75:8880/current_battle?json=1";
var EOLurl = "http://elmaonline.net/battles/";
var timer;

// XHR requests, with promises
function getURL(url) {
  return new Promise((resolve, reject) => {
    var req = new XMLHttpRequest();
    req.open('GET', url);

    req.onload = () => {
      if (req.status == 200) {
        resolve(req.responseText);
      } else {
        reject(Error(req.statusText));
      }
    };

    req.onerror = () => {
      reject(Error("Network Error"));
    };

    req.send();
  });
}

// sets extension icon badge color based on time left of battle
function setTimeIndicatorIcon (timeState) {
  switch (timeState) {
    case 'green':
      chrome.browserAction.setBadgeText({text: "\u00A0"}); // invisible character
      chrome.browserAction.setBadgeBackgroundColor({color:[106, 161, 33, 255]});
      break;
    case 'yellow':
      chrome.browserAction.setBadgeText({text: "\u00A0"}); // invisible character
      chrome.browserAction.setBadgeBackgroundColor({color:[245, 219, 49, 255]});
      break;
    case 'red':
      chrome.browserAction.setBadgeText({text: "\u00A0"}); // invisible character
      chrome.browserAction.setBadgeBackgroundColor({color:[224, 27, 27, 255]});
      break;
    default:
      chrome.browserAction.setBadgeText({text: ''}); // empty string removes badge
      break;
  }
}


function getBattleInfo () {
  getURL(APIurl).then(response => {
    var res = JSON.parse(response);
    if (res.id) { // battle probably active if we get a battle id
      chrome.storage.sync.get("battle", result => {
        if (res.id === result.battle.id) { // if we already have battle info, skip fetching map etc.
          console.log('not new!');
        } else { // new battle, fetch map from EOL site
          getMap(res.id).then(map => {
            res.map = map;
            chrome.storage.sync.set({ "battle": res });
            console.log('new');
            console.log(res);
          });
        }
      });
    } else { // no battle active
      chrome.storage.sync.set({ "battle": {} });
      console.log('no battle');
    }
  });
}

function getMap (id) {
  return new Promise((resolve, reject) => {
    getURL(EOLurl + id).then(response => {
      var tempDOM = document.createElement('div');
      tempDOM.innerHTML = response;
      // getElementById not working for whatever reason, ghetto querySelector instead
      var map = tempDOM.querySelector('#right').getElementsByTagName("img")[0].getAttribute("src");
      resolve(map);
    });
  });
}

timer = new BattleTimer();

function BattleTimer (duration, elapsed) {
  this.duration = duration;
  this.elapsed = elapsed;
}

BattleTimer.prototype.start = function () {
  this.active = true;
  this.tick();
};

BattleTimer.prototype.tick = function (ms) {
  if (this.active) {
    // TODO: let user specify threshholds?
    // if time over half: green icon
    // if time under half, over quart: yellow icon
    // if time below quarter: red icon

    // TODO: set interval higher when new battle started:
    // Check time left, start at 2m if >2m left (in case aborted),
    // then increment down to match end of battle, then wait 2mins and 10s interval again?
    var timer = ms || 10000;
    setTimeout(() => {
      this.tick();
    }, ms);
  }
};

BattleTimer.prototype.stop = function () {
  this.active = false;
};


// new battle
function newBattle () {
  notifyBattle();
}

// notify
function notifyBattle () {

}

// start watching for new battles
function startBackground () {
  // TODO: put timers and stuff
}

// stop watching for new battles
function stopBackground () {
  setTimeIndicatorIcon(false);
  // TODO: remove timers etc. obv...
  timer.stop();
}

// start background processing
startBackground();

@@ -3759,224 +3759,8 @@
 on%0A%0A
-    // TODO: set interval higher when new battle started:%0A    // Check time left, start at 2m if %3E2m left (in case aborted),%0A    // then increment down to match end of battle, then wait 2mins and 10s interval again?%0A
     
@@ -3784,16 +3784,16 @@
  10000;%0A
+
     setT
@@ -3916,17 +3916,16 @@
 se;%0A%7D;%0A%0A
-%0A
 // new b
@@ -3983,17 +3983,24 @@
 // notif
-y
+ications
 %0Afunctio
@@ -4019,16 +4019,193 @@
 le () %7B%0A
+  chrome.notifications.create('NewBattle', %7B%0A    type: 'image',%0A    iconUrl: 'images/icon128.png',%0A    imageUrl: '',%0A    title: %22New battle%22,%0A    message: %22hello there!%22%0A    %7D);
 %0A%7D%0A%0A// s

Test notification API