
import { Component, OnInit, ViewContainerRef, Inject } from '@angular/core';
import { FormControl, FormGroup, FormBuilder, ValidatorFn, Validators } from '@angular/forms';
import { MatDatepicker } from '@angular/material';
import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material';
import { ActivatedRoute, Router } from '@angular/router';
import { TranslateService } from '@ngx-translate/core';
import { InitCommonsService, NotificationService } from '@xdf/commons';
import { AuditDialogService, ConfirmationDialogService, DynaDataService, ValidatorUtils } from '@xdf/gallery';
import { NavigationService } from '@xdf/layouts';

import { BytebotSettingsService } from 'projects/bytebot-html/src/app/services/bytebot-settings-service'
import { first } from 'rxjs/operators';

import * as moment_ from 'moment';
const moment = moment_;

export const MY_FORMATS = {
  parse: {
    dateInput: 'DD/MMM',
  },
  display: {
    dateInput: 'DD/MMM',
    monthYearLabel: 'MMM',
    dateA11yLabel: 'LL',
    monthYearA11yLabel: 'MMMM YYYY',
  },
};

@Component({
  selector: 'byte-calendar-exception-dialog',
  templateUrl: './calendar-exception-dialog.component.html',
  styleUrls: ['./calendar-exception-dialog.component.scss']
})
export class CalendarExceptionDialogComponent {
  calendarConfForm = true;
  typeList: any[];
  frequencyList: any[];
  monthList: any[];
  periodList: any[];
  weekList: any[];
  title: string;
  record;
  mode = 'view';
  form: FormGroup;
  logo: any;
  logoTipo: any;
  logoBase64: any;
  logoSrc: any;
  constructor(
    private formBuilder: FormBuilder,
    protected vcRef: ViewContainerRef,
    protected route: ActivatedRoute,
    protected router: Router,
    protected dynaDataService: DynaDataService,
    protected translate: TranslateService,
    protected auditDialogService: AuditDialogService,
    protected confirmationDialogService: ConfirmationDialogService,
    protected navigationService: NavigationService,
    protected init: InitCommonsService,
    protected validatorUtils: ValidatorUtils,
    private BytebotSettingsService: BytebotSettingsService,
    public dialogRef: MatDialogRef<CalendarExceptionDialogComponent>,
    @Inject(MAT_DIALOG_DATA) public data: any,
    protected notificationService: NotificationService) {

    // this.BytebotSettingsService.getApplicationSettings().pipe(first()).subscribe(result => {
    //   this.logo = result;
    //   this.logoTipo = this.logo.tipo;
    //   this.logoBase64 = this.logo.logoBase64;
    //   this.logoSrc = 'data:image/'.concat(this.logoTipo, ';base64,', this.logoBase64);
    // });

    this.title = this.data.title;
    this.record = this.data.record;
    this.mode = this.data.mode;
    this.typeList = [
      {
        'value': 'H',
        'label': 'type_holiday'
      },
      {
        'value': 'N',
        'label': 'type_no_work_exception'
      },
      {
        'value': 'W',
        'label': 'type_work_exception'
      }
    ];
    this.frequencyList = [
      {
        'value': 'U',
        'label': 'frequecy_unique'
      },
      {
        'value': 'R',
        'label': 'frequency_range'
      },
      {
        'value': 'Y',
        'label': 'frequecy_annual'
      },
      {
        'value': 'W',
        'label': 'frequency_unique_weekly'
      }
    ];
    this.monthList = [
      {
        'value': 1,
        'label': 'year_month_jan'
      },
      {
        'value': 2,
        'label': 'year_month_feb'
      },
      {
        'value': 3,
        'label': 'year_month_mar'
      },
      {
        'value': 4,
        'label': 'year_month_apr'
      },
      {
        'value': 5,
        'label': 'year_month_may'
      },
      {
        'value': 6,
        'label': 'year_month_june'
      },
      {
        'value': 7,
        'label': 'year_month_july'
      },
      {
        'value': 8,
        'label': 'year_month_aug'
      },
      {
        'value': 9,
        'label': 'year_month_sept'
      },
      {
        'value': 10,
        'label': 'year_month_oct'
      },
      {
        'value': 11,
        'label': 'year_month_nov'
      },
      {
        'value': 12,
        'label': 'year_month_dec'
      }
    ];
    this.periodList = [
      {
        'value': 'W',
        'label': 'period_day_week'
      },
      {
        'value': 'M',
        'label': 'period_day_month'
      }
    ];
    this.weekList = [
      {
        'value': 1,
        'label': 'week_day_sun'
      },
      {
        'value': 2,
        'label': 'week_day_mon'
      },
      {
        'value': 3,
        'label': 'week_day_tue'
      },
      {
        'value': 4,
        'label': 'week_day_wed'
      },
      {
        'value': 5,
        'label': 'week_day_thu'
      },
      {
        'value': 6,
        'label': 'week_day_fri'
      },
      {
        'value': 7,
        'label': 'week_day_sat'
      }
    ];
    this.form = new FormGroup({
      description: new FormControl({
        value: (this.record && this.record['description'] && this.mode !== 'new') ? this.record['description'] : '',
        disabled: this.mode === 'view'
      }, Validators.required),
      calendarExceptionType: new FormControl({
        value: (this.record && this.record['calendarExceptionType'] && this.mode !== 'new') ? this.record['calendarExceptionType'] : '',
        disabled: this.mode === 'view'
      }, Validators.required),
      frequencyType: new FormControl({
        value: (this.record && this.record['frequencyType'] && this.mode !== 'new') ? this.record['frequencyType'] : '',
        disabled: this.mode === 'view'
      }, Validators.required),
    });
  }


  ngOnInit() {
    if (this.record && this.record['frequencyType'] && this.mode !== 'new') {
      this.form.addControl('id', new FormControl({
        value: (this.record && this.record['id'] && this.mode !== 'id') ? this.record['id'] : null,
        disabled: this.mode === 'view'
      }));
      const keyUnique = 'U';
      const keyRange = 'R';
      const keyWeek = 'W';
      const keyYear = 'Y';
      switch (this.record['frequencyType']) {
        case keyUnique: {
          // this.form.addControl('date', new FormControl({
          //   value: (this.record && this.record['date'] && this.mode !== 'new') ? this.record['date'] : '',
          //   disabled: this.mode === 'view'
          // }, Validators.required));
          var dateRecord = this.record['date'] as String
          var date:any = this.record['date'];
          if(this.record['date'] instanceof Date){
            // var date = this.record['date'];
          } 
          else {
            var dateInfo = dateRecord.split('-');
            date = new Date(Number(dateInfo[0]),Number(dateInfo[1])-1,Number(dateInfo[2]));
          }

          this.form.addControl('date', new FormControl({
            value: (this.record && this.record['date'] && this.mode !== 'new') ? date : '',
            disabled: this.mode === 'view'
          }, Validators.required));
          break;
        }
        case keyRange: {
          this.form.addControl('to', new FormControl({
            value: (this.record && this.record['to'] && this.mode !== 'new') ? this.record['to'] : '',
            disabled: this.mode === 'view'
          }, Validators.required));
          this.form.addControl('from', new FormControl({
            value: (this.record && this.record['from'] && this.mode !== 'new') ? this.record['from'] : '',
            disabled: this.mode === 'view'
          }, Validators.required));
          break;
        }
        case keyWeek: {
          this.form.addControl('month', new FormControl({
            value: (this.record && this.record['month'] && this.mode !== 'new') ? this.record['month'] : '',
            disabled: this.mode === 'view'
          }, Validators.required));
          this.form.addControl('dayOfWeek', new FormControl({
            value: (this.record && this.record['dayOfWeek'] && this.mode !== 'new') ? this.record['dayOfWeek'] : '',
            disabled: this.mode === 'view'
          }, Validators.required));
          this.form.addControl('weekOfMonth', new FormControl({
            value: (this.record && this.record['weekOfMonth'] && this.mode !== 'new') ? this.record['weekOfMonth'] : '',
            disabled: this.mode === 'view'
          }, Validators.required));
          break;
        }
        case keyYear: {
          this.form.addControl('month', new FormControl({
            value: (this.record && this.record['month'] && this.mode !== 'new') ? this.record['month'] : '',
            disabled: this.mode === 'view'
          }));
          this.form.addControl('annual', new FormControl({
            value: this.getValueAnnual(),
            disabled: this.mode === 'view'
          }, Validators.required));
          this.form.addControl('dayOfMonth', new FormControl({
            value: (this.record && this.record['weekOfMonth'] && this.mode !== 'new') ? this.record['weekOfMonth'] : '',
            disabled: this.mode === 'view'
          }));
          break;
        }
      }
    }
    console.log(this.form.value);
  }

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

  ok() {
    const result = {};
    const keyRecord = 'record';
    const keySuccess = 'success';
    result[keyRecord] = this.form.value;
    result[keySuccess] = true;
    this.dialogRef.close(result);
    this.setValueMonth();
    console.log(this.form);
  }

  chosenYearHandler(normalizedYear: moment_.Moment) {
    const ctrlValue = this.form.value['annual'];
    ctrlValue.year(normalizedYear.year());
    this.form.controls['annual'].setValue(ctrlValue);
  }

  chosenMonthHandler(normalizedMonth: moment_.Moment, datepicker: MatDatepicker<moment_.Moment>) {
    const ctrlValue = this.form.value['annual'];
    ctrlValue.month(normalizedMonth.month());
    this.form.controls['annual'].setValue(ctrlValue);
    datepicker.close();
  }

  getValueAnnual() {
    let month;
    let day;
    if (this.record && this.record['month'] && this.record['dayOfMonth']) {
      month = this.record['month'] - 1;
      day = this.record['dayOfMonth'];
      const dateObj = new Date();
      dateObj.setMonth(month);
      dateObj.setDate(day);
      return moment(dateObj);
    } else {
      return '';
    }
  }
  setValueMonth() {
    const annual = 'annual';
    const keyMonth = 'month';
    const keyDay = 'dayOfMonth';
    if (this.form && this.form.value[annual]) {
      const dateObj = new Date(this.form.value[annual]);
      if(this.form.value['frequencyType']=='Y') this.form.value[keyDay] = dateObj.getDate();
      else this.form.value[keyDay] = dateObj.getDate() + 1;
      this.form.value[keyMonth] = dateObj.getMonth() + 1;
      console.log(this.form.value);
    }
  }
  onOptionsSelected(item) {
    const keyUnique = 'U';
    const keyRange = 'R';
    const keyWeek = 'W';
    const keyYear = 'Y';
    switch (item) {
      case keyUnique: {
        this.form.removeControl('to');
        this.form.removeControl('from');
        this.form.removeControl('month');
        this.form.removeControl('weekOfMonth');
        this.form.removeControl('annual');
        this.form.removeControl('dayOfWeek');
        this.form.removeControl('dayOfMonth');
        this.form.addControl('date', this.formBuilder.control('', [Validators.required]));
        break;
      }
      case keyRange: {
        this.form.addControl('to', this.formBuilder.control('', [Validators.required]));
        this.form.addControl('from', this.formBuilder.control('', [Validators.required]));
        this.form.removeControl('month');
        this.form.removeControl('weekOfMonth');
        this.form.removeControl('annual');
        this.form.removeControl('dayOfWeek');
        this.form.removeControl('dayOfMonth');
        this.form.removeControl('date');
        break;
      }
      case keyWeek: {
        this.form.removeControl('to');
        this.form.removeControl('from');
        this.form.addControl('month', this.formBuilder.control('', [Validators.required]));
        this.form.removeControl('dayOfMonth');
        this.form.removeControl('annual');
        this.form.addControl('dayOfWeek', this.formBuilder.control('', [Validators.required]));
        this.form.addControl('weekOfMonth', this.formBuilder.control('', [Validators.required, Validators.min(1), Validators.max(4)]));
        this.form.removeControl('date');
        break;
      }
      case keyYear: {
        this.form.removeControl('to');
        this.form.removeControl('from');
        this.form.addControl('month', this.formBuilder.control('', []));
        this.form.removeControl('weekOfMonth');
        this.form.addControl('annual', this.formBuilder.control('', [Validators.required]));
        this.form.removeControl('dayOfWeek');
        this.form.addControl('dayOfMonth', this.formBuilder.control('', []));
        this.form.removeControl('date');
        break;
      }
    }
    console.log(this.form.controls);
  }
}
