import {
  Component,
  Input,
  Output,
  EventEmitter,
  OnInit,
  ViewChild
} from '@angular/core';
import { MomentHelper } from '../../helpers/moment.helper';
import { AlertEventService } from '../alert/alert.event.service';
import { FormGroup, NgForm, AbstractControl } from '@angular/forms';
import { FormOptionsComponent } from '../form-options/form-options.component';

@Component({
  selector: 'sts-form-datepicker',
  templateUrl: './form-datepicker.component.html',
  styleUrls: ['./form-datepicker.component.scss']
})
export class FormDatepickerComponent implements OnInit {
  @Output() methodToExecute: EventEmitter<any> = new EventEmitter<any>();
  @Input() genericErrorMessage?: string = 'Unable to display control';
  @Input() defDate: string;
  selectedDay: any;
  selectedMonth: any;
  selectedYear: any;

  @Input() formGrp: FormGroup;
  @Input() nameDay: string;
  @Input() nameMonth: string;
  @Input() nameYear: string;

  @Input() formDir?: NgForm;

  day: string[];
  month: string[];
  year: string[];

  control1: AbstractControl;
  control2: AbstractControl;
  control3: AbstractControl;

  @ViewChild('monthCompt')
  monthCompt: FormOptionsComponent;

  @ViewChild('dayCompt')
  dayCompt: FormOptionsComponent;

  error: boolean = false;

  constructor(private serv: AlertEventService) { }

  ngOnInit() {
    this.initalizeControls();
    this.initializeDates();
  }

  initalizeControls() {
    this.control1 = this.formGrp.get(this.nameDay);
    this.control2 = this.formGrp.get(this.nameMonth);
    this.control3 = this.formGrp.get(this.nameYear);
  }

  initializeDates() {
    this.day = Array.from(new Array(31), (val, index) => {
      const value = (index + 1).toString();
      return value.length == 1 ? '0' + value : value;
    });
    this.month = Array.from(new Array(12), (val, index) => {
      const value = (index + 1).toString();
      return value.length == 1 ? '0' + value : value;
    });
    this.year = Array.from(new Array(150), (val, index) =>
      (index + (new Date().getFullYear() - 149)).toString()
    ).sort((a, b) => {
      return parseFloat(b) - parseFloat(a);
    });

    // Logic : if there is a date passed in, we will attempt to parse and if it fails
    // simply initiate today's date as new date. No need to show error and block user if
    // date coming from SFDC is wrong.

    if (this.defDate && MomentHelper.DateValidation(this.defDate)) {
      // simply parse date
      this.parseDate();
    }
  }

  parseDate() {
    this.selectedDay = new Date(this.defDate).getDate().toString();
    this.selectedDay =
      this.selectedDay.length == 1 ? '0' + this.selectedDay : this.selectedDay;

    this.selectedMonth = (new Date(this.defDate).getMonth() + 1).toString();
    this.selectedMonth =
      this.selectedMonth.length == 1
        ? '0' + this.selectedMonth
        : this.selectedMonth;

    this.selectedYear = new Date(this.defDate).getFullYear().toString();
    this.selectedYear =
      this.selectedYear.length == 1
        ? '0' + this.selectedYear
        : this.selectedYear;
  }

  // does not need to know if passed in obj is day, month or year
  // as this is handled at parent component
  onDropdownChange(obj: any, key: string) {
    this[key] = obj;

    const newDate =
      this.selectedYear + '-' + this.selectedMonth + '-' + this.selectedDay;

    if (MomentHelper.DateValidation(newDate)) {
      this.defDate = newDate;
      this.methodToExecute.emit(this.defDate);
    } else {
      if (
        !isNaN(this.selectedYear) &&
        !isNaN(this.selectedMonth) &&
        !isNaN(this.selectedDay)
      ) {
        this.dateErrorHandling(key);
      }
    }
  }

  dateErrorHandling(key: string) {
    this.serv.alert('Date input is invalid!');
    if (key == 'selectedDay') {
      this.dayCompt.clearControl();
    } else {
      this.monthCompt.clearControl();
    }
  }
}
