import { Controller } from "./main";

export class TimeView {
    esp_time: HTMLDivElement
    rtc_time: HTMLDivElement
    browser_time: HTMLDivElement
    sync: HTMLButtonElement
    auto_refresh: HTMLInputElement;
  controller: Controller;
  timer: NodeJS.Timeout | undefined;
  timezoneSelect: HTMLSelectElement;
  
    constructor(controller:Controller) {
      (document.getElementById("timeview") as HTMLElement).innerHTML = require("./timeview.html")
      this.timezoneSelect = document.getElementById('timezone_select') as HTMLSelectElement;
      this.timezoneSelect.onchange = function(){
        controller.configChanged()
      }

      this.auto_refresh = document.getElementById("timeview_auto_refresh") as HTMLInputElement;
      this.esp_time = document.getElementById("timeview_esp_time") as HTMLDivElement;
      this.rtc_time = document.getElementById("timeview_rtc_time") as HTMLDivElement;
      this.browser_time = document.getElementById("timeview_browser_time") as HTMLDivElement;
      this.sync = document.getElementById("timeview_time_upload") as HTMLButtonElement;
      this.sync.onclick = controller.syncRTCFromBrowser;
      this.controller = controller;

      this.auto_refresh.onchange = () => {
        if(this.timer){
          clearTimeout(this.timer)
        }
        if(this.auto_refresh.checked){
          controller.updateRTCData()
        }
      }
    }
  
    update(native: string, rtc: string) {
      this.esp_time.innerText = native;
      this.rtc_time.innerText = rtc;
      const date = new Date();
      this.browser_time.innerText = date.toISOString();
      if(this.auto_refresh.checked){
        this.timer = setTimeout(this.controller.updateRTCData, 1000);
      } else {
        if(this.timer){
          clearTimeout(this.timer)
        }
      }
      
    }

    timezones(timezones: string[]) {
      timezones.forEach(tz => {
        const option = document.createElement('option');
        option.value = tz;
        option.textContent = tz;
        this.timezoneSelect.appendChild(option);
      });

    }

  getTimeZone() {
    return this.timezoneSelect.value;
  }

  setTimeZone(timezone: string | undefined) {
    if (timezone != undefined) {
      this.timezoneSelect.value = timezone;
    } else {
      this.timezoneSelect.value = "UTC";
    }
  }
}