import { AfterViewChecked, ChangeDetectorRef, Component, Input, OnInit, Output, EventEmitter, OnDestroy } from '@angular/core';
import { FormGroup, FormControl } from '@angular/forms';
import * as moment_ from 'moment';
import { Subscription } from 'rxjs';
const moment = moment_;

const DEFAULT_FORMAT_DATE = "YYYY-MM-DD";

@Component({
  selector: 'byte-week-scheduler-form',
  templateUrl: './week-scheduler-form.component.html',
  styleUrls: ['./week-scheduler-form.component.scss']
})
export class WeekSchedulerFormComponent implements OnInit, AfterViewChecked, OnDestroy {
  form: FormGroup;
  monValidator = true;
  tueValidator = true;
  wedValidator = true;
  thuValidator = true;
  friValidator = true;
  satValidator = true;
  sunValidator = true;
  @Input() weekConfig: Array<any> = [];
  @Input() mode: string;
  @Output() dirtyChange: EventEmitter<any> = new EventEmitter<any>();

  week: string[] = ["week_day_sun", "week_day_mon", "week_day_tue", "week_day_wed", "week_day_thu", "week_day_fri", "week_day_sat"];
  changeFormSubscription: Subscription;
  constructor(
    private readonly changeDetectorRef: ChangeDetectorRef
  ) {

  }

  ngAfterViewChecked(): void {
    /*  */
    this.monValidator = this.getValidateTime(this.form.value['monFrom'], this.form.value['monTo']);
    this.tueValidator = this.getValidateTime(this.form.value['tueFrom'], this.form.value['tueTo']);
    this.wedValidator = this.getValidateTime(this.form.value['wedFrom'], this.form.value['wedTo']);
    this.thuValidator = this.getValidateTime(this.form.value['thuFrom'], this.form.value['thuTo']);
    this.friValidator = this.getValidateTime(this.form.value['friFrom'], this.form.value['friTo']);
    this.satValidator = this.getValidateTime(this.form.value['satFrom'], this.form.value['satTo']);
    this.sunValidator = this.getValidateTime(this.form.value['sunFrom'], this.form.value['sunTo']);

    this.changeDetectorRef.detectChanges();
  }
  ngOnInit() {
    this.form = this.getFields(this.mode);

    if (this.form && this.mode !== 'view') {
      this.changeFormSubscription = this.form.valueChanges.subscribe(cambios => {
        console.log('cambios');
        this.dirtyChange.emit(true);
      })
    }
  }

  ngOnDestroy() {
    if( this.changeFormSubscription ){
      this.changeFormSubscription.unsubscribe;
    }
  }

  public getFields(mode: string) {
    let validatorList = [];
    let form;
    if (mode !== 'new') {
      form = new FormGroup({
        // Día 1 (lunes)
        monConf: new FormControl({
          value: this.getvalueConf(1),
          disabled: this.getDisabledMode(mode),
        }
        ),
        monFrom: new FormControl({
          value: this.getValueDate(1, true),
          disabled: this.getDisabledMode(mode),
        }, validatorList
        ),
        monTo: new FormControl({
          value: this.getValueDate(1, false),
          disabled: this.getDisabledMode(mode),
        }, validatorList
        ),

        // Día 2 (Martes)
        tueConf: new FormControl({
          value: this.getvalueConf(2),
          disabled: this.getDisabledMode(mode),
        }, validatorList
        ),
        tueFrom: new FormControl({
          value: this.getValueDate(2, true),
          disabled: this.getDisabledMode(mode),
        }, validatorList
        ),
        tueTo: new FormControl({
          value: this.getValueDate(2, false),
          disabled: this.getDisabledMode(mode),
        }, validatorList
        ),

        // Día 3 (Miercoles)
        wedConf: new FormControl({
          value: this.getvalueConf(3),
          disabled: this.getDisabledMode(mode),
        }, validatorList
        ),
        wedFrom: new FormControl({
          value: this.getValueDate(3, true),
          disabled: this.getDisabledMode(mode),
        }, validatorList
        ),
        wedTo: new FormControl({
          value: this.getValueDate(3, false),
          disabled: this.getDisabledMode(mode),
        }, validatorList
        ),

        // Día 4 (Jueves)
        thuConf: new FormControl({
          value: this.getvalueConf(4),
          disabled: this.getDisabledMode(mode),
        }, validatorList
        ),
        thuFrom: new FormControl({
          value: this.getValueDate(4, true),
          disabled: this.getDisabledMode(mode),
        }, validatorList
        ),
        thuTo: new FormControl({
          value: this.getValueDate(4, false),
          disabled: this.getDisabledMode(mode),
        }, validatorList
        ),


        // Día 5 (Viernes)
        friConf: new FormControl({
          value: this.getvalueConf(5),
          disabled: this.getDisabledMode(mode),
        }, validatorList
        ),
        friFrom: new FormControl({
          value: this.getValueDate(5, true),
          disabled: this.getDisabledMode(mode),
        }, validatorList
        ),
        friTo: new FormControl({
          value: this.getValueDate(5, false),
          disabled: this.getDisabledMode(mode),
        }, validatorList
        ),


        // Día 6 (sabado)
        satConf: new FormControl({
          value: this.getvalueConf(6),
          disabled: this.getDisabledMode(mode),
        }, validatorList
        ),
        satFrom: new FormControl({
          value: this.getValueDate(6, true),
          disabled: this.getDisabledMode(mode),
        }, validatorList
        ),
        satTo: new FormControl({
          value: this.getValueDate(6, false),
          disabled: this.getDisabledMode(mode),
        }, validatorList
        ),


        // Día 7 (DOmingo)
        sunConf: new FormControl({
          value: this.getvalueConf(0),
          disabled: this.getDisabledMode(mode),
        }, validatorList
        ),
        sunFrom: new FormControl({
          value: this.getValueDate(0, true),
          disabled: this.getDisabledMode(mode),
        }, validatorList
        ),
        sunTo: new FormControl({
          value: this.getValueDate(0, false),
          disabled: this.getDisabledMode(mode),
        }, validatorList
        ),
      })
    }
    else {
      form = new FormGroup({
        // Día 1 (lunes)
        monConf: new FormControl({
          value: false,
          disabled: this.getDisabledMode(mode),
        }, validatorList
        ),
        monFrom: new FormControl({
          value: this.getValueDate(2, true),
          disabled: this.getDisabledMode(mode),
        }, validatorList
        ),
        monTo: new FormControl({
          value: this.getValueDate(2, false),
          disabled: this.getDisabledMode(mode),
        }, validatorList
        ),

        // Día 2 (Martes)
        tueConf: new FormControl({
          value: false,
          disabled: this.getDisabledMode(mode),
        }, validatorList
        ),
        tueFrom: new FormControl({
          value: this.getValueDate(3, true),
          disabled: this.getDisabledMode(mode),
        }, validatorList
        ),
        tueTo: new FormControl({
          value: this.getValueDate(3, false),
          disabled: this.getDisabledMode(mode),
        }, validatorList
        ),

        // Día 3 (Miercoles)
        wedConf: new FormControl({
          value: false,
          disabled: this.getDisabledMode(mode),
        }, validatorList
        ),
        wedFrom: new FormControl({
          value: this.getValueDate(4, true),
          disabled: this.getDisabledMode(mode),
        }, validatorList
        ),
        wedTo: new FormControl({
          value: this.getValueDate(4, false),
          disabled: this.getDisabledMode(mode),
        }, validatorList
        ),

        // Día 4 (Jueves)
        thuConf: new FormControl({
          value: false,
          disabled: this.getDisabledMode(mode),
        }, validatorList
        ),
        thuFrom: new FormControl({
          value: this.getValueDate(5, true),
          disabled: this.getDisabledMode(mode),
        }, validatorList
        ),
        thuTo: new FormControl({
          value: this.getValueDate(5, false),
          disabled: this.getDisabledMode(mode),
        }, validatorList
        ),


        // Día 5 (Viernes)
        friConf: new FormControl({
          value: false,
          disabled: this.getDisabledMode(mode),
        }, validatorList
        ),
        friFrom: new FormControl({
          value: this.getValueDate(6, true),
          disabled: this.getDisabledMode(mode),
        }, validatorList
        ),
        friTo: new FormControl({
          value: this.getValueDate(6, false),
          disabled: this.getDisabledMode(mode),
        }, validatorList
        ),


        // Día 6 (sabado)
        satConf: new FormControl({
          value: false,
          disabled: this.getDisabledMode(mode),
        }, validatorList
        ),
        satFrom: new FormControl({
          value: this.getValueDate(7, true),
          disabled: this.getDisabledMode(mode),
        }, validatorList
        ),
        satTo: new FormControl({
          value: this.getValueDate(7, false),
          disabled: this.getDisabledMode(mode),
        }, validatorList
        ),


        // Día 7 (DOmingo)
        sunConf: new FormControl({
          value: false,
          disabled: this.getDisabledMode(mode),
        }, validatorList
        ),
        sunFrom: new FormControl({
          value: this.getValueDate(1, true),
          disabled: this.getDisabledMode(mode),
        }, validatorList
        ),
        sunTo: new FormControl({
          value: this.getValueDate(1, false),
          disabled: this.getDisabledMode(mode),
        }, validatorList
        ),
      })
    }
    console.log(form);
    return form;
  }


  getValueDate(num: number, type: boolean) {
    let timeStr = '';
    if (this.weekConfig && this.weekConfig[num]) {
      if (type && this.weekConfig[num].from) {
        timeStr = this.weekConfig[num].from;
      } else if (this.weekConfig[num].to) {
        timeStr = this.weekConfig[num].to;
      } else {
        timeStr = '';
      }
    }
    const dateObj = new Date();
    const currentDateStr = dateObj.toISOString().split('T').shift();
    if (timeStr === '') {
      if (type) {
        timeStr = '00:00:00';
      } else {
        timeStr = '23:59:59';
      }
    }
    return moment(currentDateStr + ' ' + timeStr).toDate();
  }

  getValueTime(time: any) {
    if(!time) return '';
    return time.toString().split(' ')[4];
  }

  getValidateTime(timeFrom: any, timeTo: any) {
    let from = this.getValueTime(timeFrom);
    let to = this.getValueTime(timeTo);

    var horaInicio = moment(from, 'h:mm:ssa');
    var horaFin = moment(to, 'h:mm:ssa');

    let valueBoo = false;
    if (horaInicio.isBefore(horaFin)) {
      valueBoo = true;
    }
    return valueBoo;
  }

  toTime(timeString) {
    var timeTokens = timeString.split(':');
    return new Date(1970, 0, 1, timeTokens[0], timeTokens[1], timeTokens[2]);
  }

  getvalueConf(num: number) {
    if (this.weekConfig) {
      if (this.weekConfig[num] && this.weekConfig[num].from != null && this.weekConfig[num].from != null && this.weekConfig[num].from != '' && this.weekConfig[num].to != '') {
        return true;
      }
    }
    return false;
  }
  getValueId(num: number) {
    if (this.weekConfig) {
      if (this.weekConfig[num] && this.weekConfig[num].id != null) {
        return this.weekConfig[num].id;
      }
    }
    return null;
  }

  getDisabledMode(mode: string): boolean {
      return mode === 'view';
  }

  reLoadFields(mode){
      if (this.form.controls['monConf']) {
        this.form.controls['monConf'].enable();
      }
      if (this.form.controls['tueConf']) {
        this.form.controls['tueConf'].enable();
      }
      if (this.form.controls['wedConf']) {
        this.form.controls['wedConf'].enable();
      }
      if (this.form.controls['thuConf']) {
        this.form.controls['thuConf'].enable();
      }
      if (this.form.controls['friConf']) {
        this.form.controls['friConf'].enable();
      }
      if (this.form.controls['satConf']) {
        this.form.controls['satConf'].enable();
      }
      if (this.form.controls['sunConf']) {
        this.form.controls['sunConf'].enable();
      }
    
    this.form = this.getFields(mode);
    if(!this.changeFormSubscription){
      this.changeFormSubscription = this.form.valueChanges.subscribe(cambios => {
        console.log('cambios');
        this.dirtyChange.emit(true);
      })
    }
  }
}
