import { FormatWidth, getLocaleTimeFormat } from '@angular/common';
import { ConfigService } from '@shared/config/config.service';
import * as _moment from 'moment';


export class TimeHelper {
  config: ConfigService;
  timeFormat: string;
  timeExample: string;
  timezoneDisplay: string;
  localTimeTooltip: string;

  constructor(config: ConfigService) {
    this.config = config;
    this.timeFormat = getLocaleTimeFormat(this.config.locale, FormatWidth.Medium);
    this.timeExample = new Date().toLocaleTimeString(this.config.locale);
    this.timezoneDisplay = new Date().toLocaleString(this.config.locale, {timeZoneName:'short'}).split(' ').pop();
    this.localTimeTooltip = `${this.timezoneDisplay} time`;
  }

  processDateFieldTime(dateObj, timeControl) {
    if (dateObj) {
      if (timeControl.value) {
        const timeObj = _moment(timeControl.value, this.timeFormat);
        if (!timeObj.isValid()) {
          timeControl.setErrors({
            invalidTime: true,
            example: this.timeExample,
          });
          return {
            error: true,
          };
        } else {
          const time = timeObj.toDate();
          dateObj.setHours(time.getHours());
          dateObj.setSeconds(time.getSeconds());
          dateObj.setMinutes(time.getMinutes());
          return {
            error: false,
          };
        }
      }
    }
    return {
      error: false,
    };
  }

}
