import {EventSourceMixin, HomeHubBaseClass} from '@bthlabs/homehub-core';
import * as luxon from 'luxon';

let INSTANCE = null;

const Base = EventSourceMixin(HomeHubBaseClass, ['tick']);

export class Clock extends Base {
  static instance () {
    if (INSTANCE === null) {
      INSTANCE = new Clock();
      INSTANCE.start();
    }

    return INSTANCE;
  }
  constructor () {
    super();

    this.now = luxon.DateTime.local();
    this.timeout = null;
  }
  clearTimeout = () => {
    if (this.timeout) {
      window.clearTimeout(this.timeout);
      this.timeout = null;
    }
  }
  onTimeout = () => {
    this.clearTimeout();

    this.now = luxon.DateTime.local();
    this.fireEvent('tick');

    this.start();
  }
  start () {
    const nextMinute = this.now.set({
      second: 0,
      millisecond: 0,
    }).plus({
      minutes: 1,
    });

    const timeoutMs = this.now.until(nextMinute).toDuration().milliseconds;
    this.timeout = window.setTimeout(this.onTimeout, timeoutMs + 10);
  }
  stop () {
    this.clearTimeout();
  }
}
