import {Component, EventEmitter, Input, OnChanges, OnInit, Output, SimpleChanges} from '@angular/core';
import { FormControl, FormGroup } from '@angular/forms';
import { FormGroupUtils, ValidatorUtils } from '@xdf/gallery';
import * as moment from 'moment';

@Component({
  selector: 'byte-datepicker-select',
  templateUrl: './datepicker-select.component.html',
  styleUrls: ['./datepicker-select.component.scss']
})
export class DatepickerSelectComponent implements OnInit {

  @Input()
  placeholder: string;

  @Input()
  name: string;

  @Input()
  suggest: string;

  @Input()
  disabled = false;

  @Input()
  required = false;

  @Input()
  minDate: Date;

  @Input()
  maxDate: Date;

  @Input()
  formGroup: FormGroup;

  @Input()
  format = 'DD/MM/YYYY';

  @Output('changeDate') change = new EventEmitter<Date>();

  constructor(
    private formGroupUtils: FormGroupUtils,
    private validatorUtils: ValidatorUtils
    ) { }

  ngOnChanges(changes: SimpleChanges): void {
    this.disabled = (this.formGroup.controls[this.name] as FormControl).disabled;

  }

  changeValue(value: any): void {
    this.change.emit(value);
  }

  getDateFormat(date: Date): any {
    if (date) {
      const datem = moment(date);
      return datem.utc().format(this.format);
    }
    return null;
  }

  ngOnInit(): void {
    if (!this.formGroup) {
      this.formGroup = this.formGroupUtils.createTemporalFormGroup(this.name, '', this.disabled);
    }
    if (!this.disabled) {
      this.disabled = (this.formGroup.controls[this.name] as FormControl).disabled;
    }

  }
}
