// <link href="https://fonts.googleapis.com/css2?family=Open+Sans:wght@600&display=swap" rel="stylesheet">

Graphics.prototype.setFontOpenSans = function(scale) {
  // Actual height 48 (50 - 3)
  this.setFontCustom(
    atob('[encoded data, 4600 characters]'),
    46,
    atob("EhklJSUlJSUlJSUlEg=="),
    64+(scale<<8)+(1<<16)
  );
};

var drawTimeout;
var lastBattCheck = 0;
var batteryUsedWidth = 0;

function queueDraw(millis_now) {
    if (drawTimeout) clearTimeout(drawTimeout);
    drawTimeout = setTimeout(function () {
        drawTimeout = undefined;
        draw();
    }, 60000 - (millis_now % 60000));
}

function draw() {
    var date = new Date();
    var h = date.getHours(),
        m = date.getMinutes();
    var d = date.getDate();
    var is12Hour = (require("Storage").readJSON("setting.json", 1) || {})["12hour"];
    var dow = require("date_utils").dows(0,1)[date.getDay()];

    if ((date.getTime() >= lastBattCheck + 15*60000) || Bangle.isCharging()) {
      lastBattCheck = date.getTime();
      batteryUsedWidth = E.getBattery();
      batteryUsedWidth += batteryUsedWidth/2;
    }

    g.reset();
    g.clear();

    g.setFontOpenSans();
    g.setFontAlign(0, -1);
    if (is12Hour) {
      if (h > 12) h -= 12;
      if (h == 0) h = 12;
      g.drawString(h + ":" + ("0"+m).substr(-2), g.getWidth() / 2, 30);
    } else {
      g.drawString(("0"+h).substr(-2) + ":" + ("0"+m).substr(-2), g.getWidth() / 2, 30);
    }
    g.setFontAlign(1, -1);
    g.drawString(d, g.getWidth() -6, 98);
    g.setFont('Vector', 52);
    g.setFontAlign(-1, -1);
    g.drawString(dow.slice(0,2).toUpperCase(), 6, 103);

    g.fillRect(9,159,166,171);
    g.fillRect(167,163,170,167);
    if (Bangle.isCharging()) {
      g.setColor(1,1,0);
      g.fillRect(12,162,12+batteryUsedWidth,168);
    } else {
      g.setColor(1,0,0);
      g.fillRect(12,162,57,168);
      g.setColor(1,1,0);
      g.fillRect(58,162,72,168);
      g.setColor(0,1,0);
      g.fillRect(73,162,162,168);
    }
    if (batteryUsedWidth < 150) {
      g.setColor(g.theme.bg);
      g.fillRect(12+batteryUsedWidth+1,162,162,168);
    }

    if (Bangle.isCharging()) {
      g.setColor(1,1,0);
    } else if (batteryUsedWidth <= 45) {
      g.setColor(1,0,0);
    } else if (batteryUsedWidth <= 60) {
      g.setColor(1,1,0);
    } else {
      g.setColor(0, 1, 0);
    }
    g.fillRect(0, 90, g.getWidth(), 94);

    // widget redraw
    Bangle.drawWidgets();
    queueDraw(date.getTime());
}

Bangle.on('lcdPower', on => {
    if (on) {
        draw(); // draw immediately, queue redraw
    } else { // stop draw timer
        if (drawTimeout) clearTimeout(drawTimeout);
        drawTimeout = undefined;
    }
});

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

Bangle.setUI("clock");

Bangle.loadWidgets();
draw();

