import {BaseService, kServiceTime, kWidgetTime} from '@bthlabs/homehub-core';
import {DateTime} from 'luxon';

import {Clock} from 'src/lib/clock';

export class TimeService extends BaseService {
  static availableOffline = true;
  static kind = kServiceTime;
  static widget = kWidgetTime;
  static emptyCharacteristics () {
    return {
      locale: '',
      timeFormat: '',
      dateFormat: 'DATE_HUGE',
    };
  }
  payloadFromDateTime (now) {
    if (this.characteristics.locale) {
      now = now.setLocale(this.characteristics.locale);
    }

    let timeString = null;
    if (this.characteristics.timeFormat) {
      timeString = now.toFormat(this.characteristics.timeFormat);
    } else {
      timeString = now.toLocaleString(DateTime.TIME_SIMPLE);
    }

    let dateFormat = DateTime.DATE_HUGE;
    if (this.characteristics.dateFormat) {
      dateFormat = DateTime[this.characteristics.dateFormat];
    }

    return {
      data: {
        time: timeString,
        date: now.toLocaleString(dateFormat),
      },
    };
  }
  onClockTick = (clock) => {
    this.notify(this.payloadFromDateTime(clock.now));
  }
  initialState () {
    return this.payloadFromDateTime(Clock.instance().now);
  }
  setCharacteristics (newCharacteristics) {
    super.setCharacteristics(newCharacteristics);
    this.onClockTick(Clock.instance());
  }
  async start () {
    Clock.instance().addEventListener('tick', this.onClockTick);
  }
  async stop () {
    Clock.instance().removeEventListener('tick', this.onClockTick);
  }
}
