import { Component, OnInit, Inject } from '@angular/core';
import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material';

import { NGXLogger } from 'ngx-logger';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import moment from 'moment';

// tslint:disable-next-line: no-empty-interface
export interface ScheduleSendDialogData {
  reservationDate?: moment.Moment;
}

export interface ScheduleSendDialogResult {
  scheduleSendDate?: moment.Moment;
}

@Component({
  selector: 'ucap-message-schedule-send',
  templateUrl: './schedule-send.dialog.component.html',
  styleUrls: ['./schedule-send.dialog.component.scss']
})
export class ScheduleSendDialogComponent implements OnInit {
  scheduleSendForm: FormGroup;

  hourStep = 1;
  minuteStep = 10;

  dateIsToEarly = false;

  get selectedDate() {
    return this._selectedDate;
  }
  set selectedDate(v: moment.Moment) {
    v.hour(this.hourStep * Math.round(v.hour() / this.hourStep)).minute(
      this.minuteStep * Math.round(v.minute() / this.minuteStep)
    );
    this._selectedDate = v;
    const aa = moment().add(30, 'minutes');
    this.dateIsToEarly = v.isBefore(moment().add(30, 'minutes'));
  }
  // tslint:disable-next-line: variable-name
  private _selectedDate: moment.Moment;

  constructor(
    public dialogRef: MatDialogRef<
      ScheduleSendDialogData,
      ScheduleSendDialogResult
    >,
    @Inject(MAT_DIALOG_DATA) public data: ScheduleSendDialogData,
    private formBuilder: FormBuilder,
    private logger: NGXLogger
  ) {
    if (!!this.data.reservationDate) {
      this.selectedDate = this.data.reservationDate;
    } else {
      this.selectedDate = moment().add(1, 'hours');
    }
  }

  ngOnInit(): void {
    this.scheduleSendForm = this.formBuilder.group({
      scheduleDate: ['', [Validators.required]],
      scheduleTime: ['', [Validators.required]]
    });
  }

  onSelectedDate(date: moment.Moment) {
    this.selectedDate = date;
  }

  onHourSelected(hour: number) {
    this.selectedDate = this.selectedDate.hour(hour);
  }
  onMinuteSelected(minute: number) {
    this.selectedDate = this.selectedDate.minute(minute);
  }

  onClickPresetTommorowMorning() {
    this.selectedDate = moment()
      .add(1, 'days')
      .hour(10)
      .minute(0);
  }

  onClickPresetHour(interval: number) {
    this.selectedDate = moment().add(interval, 'hours');
  }

  onClickPresetDay(interval: number) {
    this.selectedDate = moment().add(interval, 'days');
  }

  onClickPresetTommorowAfternoon() {
    this.selectedDate = moment()
      .add(1, 'days')
      .hour(15)
      .minute(0);
  }

  onClickSend() {
    this.dialogRef.close({
      scheduleSendDate: this.selectedDate
    });
  }

  onClickCancel() {
    this.dialogRef.close({});
  }
}
