const img = require("heatshrink").decompress(atob("[encoded data, 5700 characters]"));

var battery = E.getBattery();

// Positions on screen
const timeX = 88, timeY = 52;
const dateX = 5, dateY = 180;
const battX = 172, battY = 175;

// Draw on every second if unlocked or charging, minute otherwise, start at with seconds on load
var drawTimeout;
var drawInterval = 1000;

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

// Update display and timeout on lock/unlock and charge state change
Bangle.on('lock',on=>{
  draw();
});

Bangle.on('charging',charging=>{
  draw();
});

function draw() {
  // work out how to display the current time
  var d = new Date();
  var h = d.getHours(), m = d.getMinutes();
  var time = (" "+h).substr(-2) + ":" + ("0"+m).substr(-2);
  var seconds = ("0"+d.getSeconds()).substr(-2);

  // g.clear();  // Unneeded if background image takes the whole screen

  // Draw background
  g.drawImage(img);
  g.setColor(1, 1, 1);

  // draw the current time
  g.setFontAlign(1,1); // align right bottom
  g.setFont("6x15",3);
  g.drawString(time, timeX, timeY, false);

  // Draw battery %
  g.setFont("6x15",1);
  var battStr = "";
  if(Bangle.isCharging()) {
    battStr = "+";
  }
  g.drawString(battStr + battery + "%", battX, battY, false);

  // Draw date
  g.setFontAlign(-1,1); // align left bottom
  g.setFont("6x15",2);
  var dateStr = require("locale").date(d)+"    ";
  g.drawString(dateStr, dateX, dateY, false);

  // draw the seconds only if unlocked, set next timeout
  if(!Bangle.isLocked() || Bangle.isCharging()) {
    drawInterval = 1000;
    g.setFont("6x15",2);
    g.drawString(seconds, timeX+2, timeY-4, false);
  }
  else
    drawInterval = 60000;

  // Schedule next draw
  queueDraw();
  // console.log("Draw " + time + ":" + seconds);
}

function refreshBattery() {
  battery = E.getBattery();
}

// Only update displayed battery level every minute as it fluctuates a lot
var batteryInterval = setInterval(refreshBattery, 60000);

Bangle.setUI("clock");
Bangle.setLocked(false);
// Clear the screen once, at startup
g.clear();
// draw immediately at first
draw();
