// Clock by Giles Booth for BangleJS2 using Büro Destruct Console Remix font
// based on code in https://www.espruino.com/Bangle.js+Clock+Font

Graphics.prototype.setFontBDGemini = function() {
  // Actual height 79 (84 - 6)
  var widths = atob("Gio1KS8zNS8vLzkvGg==");
  var font = atob("[encoded data, 9344 characters]");
  var scale = 1; // size multiplier for this font
  g.setFontCustom(font, 46, widths, 96+(scale<<8)+(1<<16));
};

// timeout used to update every minute
var drawTimeout;

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


function draw() {
  g.reset();  
  // work out locale-friendly date/time
  var date = new Date();
  var timeStr = require("locale").time(date,1);
  var hh = timeStr.substr(0,2);
  // Kludge to add leading zeros to hours - if recoding please implement leading zeros:
  // Leading zeroes are an integral part of the design.
  // If the hour is single digit the first character of the string will be 
  // space, in which case a zero is added. As there is no space in the font, 
  // spaces are ignored.
  if (hh.substr(0,1) == ' ') {
    hh = '0' + hh;
  }
  var mm = timeStr.substr(-3);
  var dayName = require("locale").dow(new Date(), 1);
  var longDateStr = date.getDate() + ' ' + require("locale").month(new Date(), 1);  
  // draw time
  g.setFont("BDGemini");
  g.clearRect(0,24,175,175); // clear the background
  g.drawString(hh,0,24);
  g.drawString(mm,49,98);
  // draw date
  g.setFont("6x8",2);
  g.drawString(dayName,106,35);
  g.drawString(longDateStr,106,51);
  g.drawString(date.getFullYear(),106,67);
  // queue draw in one minte
  queueDraw();
}

// Clear the screen once, at startup
g.clear();
// draw immediately at first, queue update
draw();
// Stop updates when LCD is off, restart when on
Bangle.on('lcdPower',on=>{
  if (on) {
    draw(); // draw immediately, queue redraw
  } else { // stop draw timer
    if (drawTimeout) clearTimeout(drawTimeout);
    drawTimeout = undefined;
  }
});
// Show launcher when middle button pressed
Bangle.setUI("clock");
// Load widgets
Bangle.loadWidgets();
Bangle.drawWidgets();