import { Component, Vue } from 'vue-property-decorator';
import moment from 'moment/moment';
import { HOLYDAYS } from '@/recruits/utils';
import { notifyError } from '@utils/notify';

const START_HOUR = 8;
const END_HOUR = 20;
const SUMMON_DELAY = 1;
const CALENDAR_DATE_FORMAT = 'YYYY/MM/DD';
const ISO_DATE_FORMAT = 'YYYY-MM-DDTHH:mm:ss.SSSZ';

@Component({})
export default class SummonDate extends Vue {
  summonDate: string | null = null;

  isDateAvailable(date: string): boolean {
    const currantDate: string = moment().format(CALENDAR_DATE_FORMAT);
    // Потом попросят нотификашку разделить
    if (HOLYDAYS.includes(moment(date).get('day'))) return false;
    // Если текущий день, проверяем на доступность времени
    return date === currantDate
      ? this.isTimeAvailable(this.getNextAvailableHour(), null, null, true) &&
          this.isTimeAvailable(
            this.getNextAvailableHour(),
            moment().minute(),
            null,
            true
          )
      : date > currantDate && !HOLYDAYS.includes(moment(date).get('day'));
  }

  isWorkHour(hour: number, isCurrentDate = false): boolean {
    return (
      hour >= START_HOUR &&
      (isCurrentDate ? hour <= END_HOUR - SUMMON_DELAY : hour < END_HOUR)
    );
  }

  getNextAvailableHour(): number {
    return moment().hour() + SUMMON_DELAY;
  }

  isTimeAvailable(
    hr: number,
    min: number | null,
    sec: number | null = null,
    isCurrentDate: boolean = this.momentSummonDate.format(
      CALENDAR_DATE_FORMAT
    ) === moment().format(CALENDAR_DATE_FORMAT)
  ): boolean {
    if (isCurrentDate) {
      if (min !== null)
        return hr !== this.getNextAvailableHour() || min >= moment().minute();
      return hr >= this.getNextAvailableHour() && this.isWorkHour(hr, true);
    }
    return !!min || this.isWorkHour(hr, false);
  }

  isDateAndTimeValid(): boolean {
    if (
      !this.isDateAvailable(this.momentSummonDate.format(CALENDAR_DATE_FORMAT))
    ) {
      notifyError('Выбран выходной день.');
      return false;
    }
    if (
      !this.isTimeAvailable(this.momentSummonDate.hour(), null) ||
      !this.isTimeAvailable(
        this.momentSummonDate.hour(),
        this.momentSummonDate.minute()
      )
    ) {
      notifyError(
        'Время вызова должно быть с 8:00 до 20:00 и не ранее, чем через час.'
      );
      return false;
    }
    return true;
  }

  get defaultYearMonth(): string {
    let date = moment();
    while (!this.isDateAvailable(date.format(CALENDAR_DATE_FORMAT))) {
      date = date.add(1, 'day');
    }
    return date.format('YYYY/MM');
  }

  get momentSummonDate(): moment.Moment {
    return moment(this.summonDate);
  }

  get isoDateFormat(): string {
    return ISO_DATE_FORMAT;
  }
}
