import { Component, Inject, OnInit } from '@angular/core';
import { FormControl, Validators } from '@angular/forms';
import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog';
import { MatSnackBar } from '@angular/material/snack-bar';

@Component({
  selector: 'app-new-instruction',
  templateUrl: './new-instruction.component.html',
  styleUrls: ['./new-instruction.component.css']
})
export class NewInstructionComponent implements OnInit {
  isNew: boolean;
  hours: string[];
  hoursNum: number[];

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

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

  constructor(
    @Inject(MAT_DIALOG_DATA) private _data: any,
    private _dialogRef: MatDialogRef<NewInstructionComponent>,
    private _snackBar: MatSnackBar,
  ) { 
    this.isNew = true;
    this.hours = [];
    this.hoursNum = [];
    
    this.startDate = null;
    this.endDate = null;
    this.startHour = null;
    this.endHour = null;
  }

  ngOnInit(): void {
    this.isNew = this._data.action == 'new';
    if(!this.isNew){
      let startDateTimeArr = this._data.instruction.INICIO.split(' ');
      let startTimeArr = startDateTimeArr[1].split('');
      let startTimeStr = `${startTimeArr[0]}${startTimeArr[1]}${startTimeArr[3]}${startTimeArr[4]}`;
      let startDateArr = startDateTimeArr[0].split('-');
      
      this.startDate = new Date(parseInt(startDateArr[0]), parseInt(startDateArr[1]) - 1, parseInt(startDateArr[2]));
      this.startHour = parseInt(startTimeStr);

      
      let endDateTimeArr = this._data.instruction.FIN.split(' ');
      let endTimeArr = endDateTimeArr[1].split('');
      let endTimeStr = `${endTimeArr[0]}${endTimeArr[1]}${endTimeArr[3]}${endTimeArr[4]}`;
      let endDateArr = endDateTimeArr[0].split('-');
      
      this.endDate = new Date(parseInt(endDateArr[0]), parseInt(endDateArr[1]) - 1, parseInt(endDateArr[2]));
      this.endHour = parseInt(endTimeStr);
      
      this.instructionControl.setValue(this._data.instruction.INSTRUCCION);
    }

    for(let i = 0; i < 24; i++){
      let period = i < 12 ? 'AM' : 'PM';
      let hour = i > 12 ? i - 12 : i;
      let hourCent = i * 100;
      
      this.hours.push(`${hour}:00 ${period}`);
      this.hoursNum.push(hourCent);

      this.hours.push(`${hour}:15 ${period}`);
      this.hoursNum.push(hourCent + 15);
      
      this.hours.push(`${hour}:30 ${period}`);
      this.hoursNum.push(hourCent + 30);
      
      this.hours.push(`${hour}:45 ${period}`);
      this.hoursNum.push(hourCent + 45);
    }
  }

  addInstruction(){
    if(this.startDate == null || this.endDate == null || this.startHour == null || this.endHour == null || 
    this.instructionControl.invalid){
      this.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}`);
    }
  }
  
  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.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.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);
  }

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

  openSnackBar(msg: string){
    this._snackBar.open(msg, undefined, {
      duration: 2500,
    });
  }
}
