Graphics.prototype.setFontAnton = function(scale) {
// Actual height 69 (68 - 0)
  g.setFontCustom(atob(" "), 46, atob("EiAnGicnJycnJycnEw=="), 78+(scale<<8)+(1<<16));
};

var SunCalc = require("suncalc"); // from modules folder
const LOCATION_FILE = "mylocation.json";
let location;
var sunRise = "--:--";
var sunSet = "--:--";
var sunIcons = "\0" + atob("DwyBAAAAAAAAAAgAOAD4A/gP+D/4//gAAAAA") + "\0" + atob("FQyDAAAAAAAAAAAAAAAABAAAAAAABAAIABAAAAABAAABAAAAAAABJAAAAABAAJJJIABAABAJJJJIBAAAAJJJJJIAAAAJJJJJJIAAJBJJJJJJBIAAJJJJJJIAAAAAAAAAAAAA") + "\0" + atob("DwyBAAAAAAAAA//j/4P+A/gD4AOAAgAAAAAA");

function loadLocation() {
  location = require('Storage').readJSON(LOCATION_FILE, true) || {lat:51.5072,lon:0.1276,location:"London"};
}

function updateSunRiseSunSet(location) {
  var times = SunCalc.getTimes(new Date(), location.lat, location.lon);
  sunRise = require("locale").time(times.sunrise, 1);
  sunSet = require("locale").time(times.sunset, 1);
}

var timerclk = require("timerclk.lib.js");
var settings = require('Storage').readJSON("timerclk.json", true) || {};
settings = Object.assign({
  "timeFont":"Anton",
  "timeFontSize":0,
  "dateFont":"6x8",
  "dateFontSize":2,
  "dowFont":"6x8",
  "dowFontSize":2,
  "srssFont":"6x8",
  "srssFontSize":2,
  "specialFont":"6x8",
  "specialFontSize":2,
  "shortDate":true,
  "showStopwatches":true,
  "showTimers":true,
  "showSrss":false,
}, settings.clock||{});

var stopwatches = [], timers = [];
if (settings.showStopwatches) {
  stopwatches = require("Storage").readJSON("timerclk.stopwatch.json") || [];
  stopwatches = stopwatches.filter(e=>e.start||e.time);
}
if (settings.showTimers) {
  timers = require("Storage").readJSON("timerclk.timer.json") || [];
  timers = timers.filter(e=>e.start||e.timeAdd);
}

// timeout used to update every minute
var drawTimeout;
var drawSpecialTimeout;
// border between time and date/dow
var dragBorder = g.getHeight()/2;

// schedule a draw for the next minute
function queueDraw(timeout, interval, func) {
  if (timeout) clearTimeout(timeout);
  timeout = setTimeout(function() {
    timeout = undefined;
    func();
  }, interval - (Date.now() % interval));
}

function drawSpecial() {
  var interval = 60000;
  var stopwatch = 0, timer = 0, time;
  var x = g.getWidth()/4;
  g.setColor(g.theme.fg);
  g.setFontAlign(0,0).setFont(settings.specialFont, settings.specialFontSize);
  var y = Bangle.appRect.y + g.stringMetrics("00:00").height/2;
  g.clearRect(Bangle.appRect.x, Bangle.appRect.y, Bangle.appRect.x2, Bangle.appRect.y+g.stringMetrics("00:00").height);

  if (stopwatches.length) {
    time = timerclk.getTime(stopwatches[stopwatch]);
    g.drawString(timerclk.formatTime(time, true), x, y);
    if (Math.floor(time/3600000) === 0) interval = 1000;
    stopwatch++;
  } else if (timers.length > 1) {
    time = timers[timer].time - timerclk.getTime(timers[timer]);
    g.drawString(timerclk.formatTime(time, true), x, y);
    if (Math.floor(time/3600000) === 0) interval = 1000;
    timer++;
  }
  x += g.getWidth()/2;
  if (timers.length) {
    time = timers[timer].time - timerclk.getTime(timers[timer]);
    g.drawString(timerclk.formatTime(time, true), x, y);
    if (Math.floor(time/3600000) === 0) interval = 1000;
  } else if (stopwatches.length > 1) {
    time = timerclk.getTime(stopwatches[stopwatch]);
    g.drawString(timerclk.formatTime(time, true), x, y);
    if (Math.floor(time/3600000) === 0) interval = 1000;
  }
  queueDraw(drawSpecialTimeout, interval, drawSpecial);
}

var drawCount=0;

function draw() {
  if (drawCount++ % 60 == 0) {
    updateSunRiseSunSet(location);
  }
  var x = g.getWidth()/2;
  var y = g.getHeight()/2;
  g.reset();
  var date = new Date();
  var timeStr = require("locale").time(date,1);
  var dateStr = require("locale").date(date,settings.shortDate).toUpperCase();
  var dowStr = require("locale").dow(date).toUpperCase();
  var srssStr = sunRise + sunIcons + sunSet;

  // draw time
  if (settings.timeFont == "Anton") {
    g.setFontAlign(0,0).setFont("Anton");
  } else {
    g.setFontAlign(0,0).setFont(settings.timeFont, settings.timeFontSize);
  }
  g.clearRect(Bangle.appRect.x, x-g.stringMetrics(timeStr).height/2, Bangle.appRect.x2, Bangle.appRect.y2); // clear the background
  g.drawString(timeStr,x,y);
  // draw date
  y += g.stringMetrics(timeStr).height/2;
  g.setFontAlign(0,0).setFont(settings.dateFont, settings.dateFontSize);
  dragBorder = y;
  y += g.stringMetrics(dateStr).height/2;
  g.drawString(dateStr,x,y);
  //draw day of week
  y += g.stringMetrics(dateStr).height/2;
  g.setFontAlign(0,0).setFont(settings.dowFont, settings.dowFontSize);
  y += g.stringMetrics(dowStr).height/2;
  g.drawString(dowStr,x,y);
  if (settings.showSrss) {
    // draw sun rise sun set
    y += g.stringMetrics(dowStr).height/2;
    g.setFontAlign(0,0).setFont(settings.srssFont, settings.srssFontSize);
    y += g.stringMetrics(srssStr).height/2;
    g.drawString(srssStr,x,y);
  }
  // queue draw in one minute
  queueDraw(drawTimeout, 60000, draw);
}

if (process.env.HWVERSION==1) {
  setWatch(()=>load("timerclk.stopwatch.js"), BTN4);
  setWatch(()=>load("timerclk.timer.js"), BTN5);
  setWatch(()=>load("timerclk.alarm.js"), BTN3);
  setWatch(()=>load("timerclk.alarm.js"), BTN1);
} else {
  var absY, lastX, lastY;
  Bangle.on('drag', e=>{
    if (!e.b) {
      if (lastX > 50) { // right
        if (absY < dragBorder) { // drag over time
          load("timerclk.timer.js");
        }else { // drag over date/dow
          load("timerclk.alarm.js");
        }
      } else if (lastX < -50) { // left
        if (absY < dragBorder) { // drag over time
          load("timerclk.stopwatch.js");
        }else { // drag over date/dow
          load("timerclk.alarm.js");
        }
      } else if (lastY > 50) { // down
      } else if (lastY < -50) { // up
      }
      lastX = 0;
      lastY = 0;
    } else {
      lastX = lastX + e.dx;
      lastY = lastY + e.dy;
      absY = e.y;
    }
  });
}

Bangle.setUI("clock"); // Show launcher when middle button pressed
g.clear();
Bangle.loadWidgets();
Bangle.drawWidgets();
loadLocation();
draw();
if (stopwatches || timers) drawSpecial();
