import document from "document";
import clock from "clock";
import { preferences } from "user-settings";

let currminutes = 99;

let dots = document.getElementById('dots');

let digits = {};
let colors = document.getElementById('colors');
digits.digit1 = document.getElementById('d1');
digits.digit2 = document.getElementById('d2');
digits.digit3 = document.getElementById('d3');
digits.digit4 = document.getElementById('d4');


function startAnimation() {
  setTimeout(() => { colors.animate('enable'); }, 5000);
}

function updateClock(force) {
  let currDate = new Date();
  let seconds = currDate.getSeconds();
  let minutes = currDate.getMinutes();
  if (seconds%2) {
    dots.animate('disable');
  } else {
    dots.animate('enable');
  }
  
  if (force || currminutes != minutes) {
    currminutes = minutes;
    digits.digit1.animate('disable');
    setTimeout(() => { digits.digit2.animate('disable'); }, 250);
    setTimeout(() => { digits.digit3.animate('disable'); }, 500);
    setTimeout(() => { digits.digit4.animate('disable'); }, 750);
    setTimeout(() => { newDigits(); }, 1000);
    setTimeout(() => { digits.digit1.animate('enable'); }, 1250);
    setTimeout(() => { digits.digit2.animate('enable'); }, 1500);
    setTimeout(() => { digits.digit3.animate('enable'); }, 1750);
    setTimeout(() => { digits.digit4.animate('enable'); }, 2000);
    
    setTimeout(() => { digits.digit1.animate('disable'); }, 2000);
    setTimeout(() => { digits.digit2.animate('disable'); }, 2250);
    setTimeout(() => { digits.digit3.animate('disable'); }, 2500);
    setTimeout(() => { digits.digit4.animate('disable'); }, 2750);
    setTimeout(() => { digits.digit1.animate('enable'); }, 3250);
    setTimeout(() => { digits.digit2.animate('enable'); }, 3500);
    setTimeout(() => { digits.digit3.animate('enable'); }, 3750);
    setTimeout(() => { digits.digit4.animate('enable'); }, 3000);
  }
}

function newDigits() {
  let currDate = new Date();
  let hours = currDate.getHours();
  let displayHours = hours;
  if (preferences.clockDisplay === '12h') {
    displayHours = displayHours % 12;
    displayHours = displayHours ? displayHours : 12;
  }
  let minutes = currDate.getMinutes();
  
  let newDigits = [
    Math.floor(displayHours/10),
    displayHours%10,
    Math.floor(minutes/10),
    minutes%10
  ];
  
  digits.digit1.href = (newDigits[0] == 0) ? '' : 'img/1-'+newDigits[0]+'.png';
  digits.digit2.href = 'img/2-'+newDigits[1]+'.png';
  digits.digit3.href = 'img/3-'+newDigits[2]+'.png';
  digits.digit4.href = 'img/4-'+newDigits[3]+'.png';
}

clock.granularity = "seconds";
clock.ontick = () => updateClock();
setTimeout(() => { updateClock(true); }, 250);

startAnimation();