import { Component, Inject, OnInit } from '@angular/core';
import { FormControl, Validators } from '@angular/forms';
import { MAT_DIALOG_DATA, MatDialog, MatDialogRef } from '@angular/material/dialog';
import { ResourcesService } from '../../../../../services/resources.service';
import { TimePickerComponent } from '../../../../resources/dialogs/time-picker/time-picker.component';

@Component({
    selector: 'app-new-instruction',
    templateUrl: './new-instruction.component.html',
    styleUrl: './new-instruction.component.css',
    standalone: false
})
export class NewInstructionComponent implements OnInit {
  isNew: boolean;
  hoursArr: any[];

  startDate: Date | null;
  endDate: Date | null;
  startHour: string | null;
  endHour: string | null;

  minDate: Date | null;
  maxDate: Date | null;

  instructionControl = new FormControl('', [Validators.required, Validators.minLength(20)]);

  constructor(
    @Inject(MAT_DIALOG_DATA) private _data: any,
    private _dialogRef: MatDialogRef<NewInstructionComponent>,
    private _dialog: MatDialog,
    private _resourcesService: ResourcesService,
  ) { 
    this.isNew = true;
    this.hoursArr = [];
    
    this.startDate = null;
    this.endDate = null;
    this.startHour = null;
    this.endHour = null;

    this.minDate = null;
    this.maxDate = null;
  }

  ngOnInit(): void {
    this.minDate = this._data.startDate;
    this.maxDate = this._data.endDate;
    this.isNew = this._data.action == 'new';

    if(!this.isNew){
      let startDateTimeArr = this._data.instruction.INICIO.split(' ');
      let startDateArr = startDateTimeArr[0].split('-');
      
      this.startDate = new Date(parseInt(startDateArr[0]), parseInt(startDateArr[1]) - 1, parseInt(startDateArr[2]));
      this.startHour = `${startDateTimeArr[1]} ${startDateTimeArr[2]}`;
      
      let endDateTimeArr = this._data.instruction.FIN.split(' ');
      let endDateArr = endDateTimeArr[0].split('-');
      
      this.endDate = new Date(parseInt(endDateArr[0]), parseInt(endDateArr[1]) - 1, parseInt(endDateArr[2]));
      this.endHour = `${endDateTimeArr[1]} ${endDateTimeArr[2]}`;
      
      this.instructionControl.setValue(this._data.instruction.INSTRUCCION);
    }

    this.fillHours();
  }

  fillHours(){
    for(let i = 0; i  < 24; i++){
      let period = i < 12 ? 'AM' : 'PM';
      let hourInt = i > 12 ? i - 12 : i;
      let hourStr = hourInt < 10 ? `0${hourInt}` : `${hourInt}`;
      let hour = i < 10 ? `0${i}` : `${i}`;

      this.hoursArr.push({ value: `${hour}:00:00`, label: `${hourStr}:00 ${period}` });
      this.hoursArr.push({ value: `${hour}:15:00`, label: `${hourStr}:15 ${period}` });
      this.hoursArr.push({ value: `${hour}:30:00`, label: `${hourStr}:30 ${period}` });
      this.hoursArr.push({ value: `${hour}:45:00`, label: `${hourStr}:45 ${period}` });
    }
  }
  
  verifyDateTime(type: string){
    if(type == 'start' && this.startHour != null && this.startDate != null){
      let startDateStr = `${this.startDate.getFullYear()}-${this.startDate.getMonth() + 1}-${this.startDate.getDate()}`;
      let startHourArr = `${this.startHour}`.split('');
      let startTimeStr = '';

      if(startHourArr.length >= 0 && startHourArr.length < 2){
        startTimeStr = '00:00';
      }else if(startHourArr.length >= 2 && startHourArr.length < 3){
        startTimeStr = `00:${this.startHour}`;
      }else if(startHourArr.length >= 3 && startHourArr.length < 4){
        startTimeStr = `0${startHourArr[0]}:${startHourArr[1]}${startHourArr[2]}`;
      }else if(startHourArr.length >= 4){
        startTimeStr = `${startHourArr[0]}${startHourArr[1]}:${startHourArr[2]}${startHourArr[3]}`;
      }

      let startDateTimeStr = `${startDateStr} ${startTimeStr}:00`;
      let startDateTime = new Date(startDateTimeStr);
      let startTimestamp = startDateTime.getTime();
      
      if(this.endHour != null && this.endDate != null){
        let endDateStr = `${this.endDate.getFullYear()}-${this.endDate.getMonth() + 1}-${this.endDate.getDate()}`;
        let endHourArr = `${this.endHour}`.split('');
        let endTimeStr = '';

        if(endHourArr.length >= 0 && endHourArr.length < 2){
          endTimeStr = '00:00';
        }else if(endHourArr.length >= 2 && endHourArr.length < 3){
          endTimeStr = `00:${this.endHour}`;
        }else if(endHourArr.length >= 3 && endHourArr.length < 4){
          endTimeStr = `0${endHourArr[0]}:${endHourArr[1]}${endHourArr[2]}`;
        }else if(endHourArr.length >= 4){
          endTimeStr = `${endHourArr[0]}${endHourArr[1]}:${endHourArr[2]}${endHourArr[3]}`;
        }

        let endDateTimeStr = `${endDateStr} ${endTimeStr}:00`;
        let endDateTime = new Date(endDateTimeStr);
        let endTimestamp = endDateTime.getTime();
        
        if(startTimestamp > endTimestamp){
          this._resourcesService.openSnackBar('La hora de inicio no puede ser mayor a la hora de término.');
          setTimeout(() => this.startHour = null, 250);
        }
      }
    }else if(type == 'end' && this.endHour != null && this.endDate != null){
      let endDateStr = `${this.endDate.getFullYear()}-${this.endDate.getMonth() + 1}-${this.endDate.getDate()}`;
      let endHourArr = `${this.endHour}`.split('');
      let endTimeStr = '';

      if(endHourArr.length >= 0 && endHourArr.length < 2){
        endTimeStr = '00:00';
      }else if(endHourArr.length >= 2 && endHourArr.length < 3){
        endTimeStr = `00:${this.endHour}`;
      }else if(endHourArr.length >= 3 && endHourArr.length < 4){
        endTimeStr = `0${endHourArr[0]}:${endHourArr[1]}${endHourArr[2]}`;
      }else if(endHourArr.length >= 4){
        endTimeStr = `${endHourArr[0]}${endHourArr[1]}:${endHourArr[2]}${endHourArr[3]}`;
      }

      let endDateTimeStr = `${endDateStr} ${endTimeStr}:00`;
      let endDateTime = new Date(endDateTimeStr);
      let endTimestamp = endDateTime.getTime();

      if(this.startHour != null && this.startDate != null){
        let startDateStr = `${this.startDate.getFullYear()}-${this.startDate.getMonth() + 1}-${this.startDate.getDate()}`;
        let startHourArr = `${this.startHour}`.split('');
        let startTimeStr = '';
  
        if(startHourArr.length >= 0 && startHourArr.length < 2){
          startTimeStr = '00:00';
        }else if(startHourArr.length >= 2 && startHourArr.length < 3){
          startTimeStr = `00:${this.startHour}`;
        }else if(startHourArr.length >= 3 && startHourArr.length < 4){
          startTimeStr = `0${startHourArr[0]}:${startHourArr[1]}${startHourArr[2]}`;
        }else if(startHourArr.length >= 4){
          startTimeStr = `${startHourArr[0]}${startHourArr[1]}:${startHourArr[2]}${startHourArr[3]}`;
        }
  
        let startDateTimeStr = `${startDateStr} ${startTimeStr}:00`;
        let startDateTime = new Date(startDateTimeStr);
        let startTimestamp = startDateTime.getTime();

        if(endTimestamp < startTimestamp){
          this._resourcesService.openSnackBar('La hora de término no puede ser menor a la hora de inicio.');
          setTimeout(() => this.endHour = null, 250);
        }
      }
    }
  }

  clearStartDate(event: any){
    event.stopPropagation();
    setTimeout(() => this.startDate = null, 250);
  }

  openTimePicker(type: string){
    let time = type == 'start' ? this.startHour : this.endHour;
    let dialogRef = this._dialog.open(TimePickerComponent, {
      data: {
        time: time,
      }
    });

    dialogRef.afterClosed().subscribe(res => {
      if(res != null && res != undefined && res != ''){
        if(type == 'start'){
          this.startHour = res;
        }else{
          this.endHour = res;
        }
        
        this.verifyDateTime(type);
      }
    });
  }

  clearEndDate(event: any){
    event.stopPropagation();
    setTimeout(() => this.endDate = null, 250);
  }

  addInstruction(){
    if(this.startDate == null || this.endDate == null || this.startHour == null || this.endHour == null || 
    this.instructionControl.invalid){
      this._resourcesService.openSnackBar('Complete los campos obligatorios.');
    }else{
      let instructionObj = {
        instruction: this.instructionControl.value,
        startDate: this.startDate,
        endDate: this.endDate,
        startHour: this.startHour,
        endHour: this.endHour
      };

      let instructionStr = JSON.stringify(instructionObj);
      this._dialogRef.close(`${instructionStr}`);
    }
  }
}
