import { Component, Inject, OnInit } from '@angular/core';
import { FormControl } from '@angular/forms';
import { MAT_DIALOG_DATA, MatDialog, MatDialogRef } from '@angular/material/dialog';
import { SpecificValueComponent } from '../specific-value/specific-value.component';

@Component({
    selector: 'app-time-picker',
    templateUrl: './time-picker.component.html',
    styleUrl: './time-picker.component.css',
    standalone: false
})
export class TimePickerComponent implements OnInit {
  hoursArr: string[];
  minusArr: string[];
  hourInd: number;
  minsInd: number;

  hourControl = new FormControl('');
  minsControl = new FormControl('');
  periodControl = new FormControl('');

  isAM: boolean;
  isPM: boolean;

  constructor(
    @Inject(MAT_DIALOG_DATA) private _data: any,
    private _dialogRef: MatDialogRef<TimePickerComponent>,
    private _dialog: MatDialog,
  ) { 
    this.hoursArr = [];
    this.minusArr = [];

    this.hourInd = 0;
    this.minsInd = 0;

    this.isAM = true;
    this.isPM = false;
  }

  ngOnInit(): void {
    for(let hour = 0; hour < 12; hour++){
      if(hour < 10){
        this.hoursArr.push(`0${hour}`);
      }else{
        this.hoursArr.push(`${hour}`);
      }
    }

    for(let minute = 0; minute < 60; minute++){
      if(minute < 10){
        this.minusArr.push(`0${minute}`);
      }else{
        this.minusArr.push(`${minute}`);
      }
    }

    if(this._data.time == null){
      this.hourControl.setValue(this.hoursArr[0]);
      this.minsControl.setValue(this.minusArr[0]);
    }else{
      let timeArr = this._data.time.split(' ');

      if(timeArr.length == 2){
        this.isAM = timeArr[1] == 'AM';
        this.isPM = timeArr[1] == 'PM';

        let hourArr = timeArr[0].split(':');
        let hourInd = this.hoursArr.indexOf(hourArr[0]);
        this.hourControl.setValue(this.hoursArr[hourInd]);

        let minsInd = this.minusArr.indexOf(hourArr[1]);
        this.minsControl.setValue(this.minusArr[minsInd]);

        this.hourInd = hourInd;
        this.minsInd = minsInd;
      }else{
        this.hourControl.setValue(this.hoursArr[0]);
        this.minsControl.setValue(this.minusArr[0]);
      }
    }
  }

  changeHour(type: string){
    if(type == 'inc'){
      let indAux = this.hourInd + 1;
      if(indAux >= this.hoursArr.length){
        this.hourInd = 0;
      }else{
        this.hourInd++;
      }
    }else{
      let indAux = this.hourInd - 1;
      if(indAux < 0){
        this.hourInd = this.hoursArr.length - 1;
      }else{
        this.hourInd--;
      }
    }

    this.hourControl.setValue(this.hoursArr[this.hourInd]);
  }

  changeMinute(type: string){
    if(type == 'inc'){
      let indAux = this.minsInd + 1;
      if(indAux >= this.minusArr.length){
        this.minsInd = 0;
      }else{
        this.minsInd++;
      }
    }else{
      let indAux = this.minsInd - 1;
      if(indAux < 0){
        this.minsInd = this.minusArr.length - 1;
      }else{
        this.minsInd--;
      }
    }

    this.minsControl.setValue(this.minusArr[this.minsInd]);
  }

  changePeriod(period: string){
    if(period == 'am'){
      this.hoursArr[0] = '00';
      
      this.isAM = true;
      this.isPM = false;
    }else{
      this.hoursArr[0] = '12';

      this.isAM = false;
      this.isPM = true;
    }

    this.hourControl.setValue(this.hoursArr[this.hourInd]);
  }

  saveTime(){
    let hourStr = this.hourControl.value;
    let minsStr = this.minsControl.value;
    let periodStr = this.isAM ? 'AM' : 'PM';
    let timeStr = `${hourStr}:${minsStr} ${periodStr}`;

    this._dialogRef.close(timeStr);
  }

  openSpecificValue(value: string, type: string){
    let dialogRef = this._dialog.open(SpecificValueComponent, {
      width: '420px',
      maxWidth: '420px',
      disableClose: true,
      data: {
        value: value,
      }
    });

    dialogRef.afterClosed().subscribe(res => {
      if(res != null && res != undefined && res != ''){
        let specificValue = parseInt(res);
        if(!isNaN(specificValue)){
          if(type == 'hour'){
            this.processHours(specificValue);
          }else if(type == 'minute'){
            let hours = Math.trunc(specificValue / 60);
            let overflowedMinute = hours * 60;
            let realMiunute = specificValue - overflowedMinute;
            let currentHourSelected = this.isPM ? this.hourInd + 12 : this.hourInd;
            let newHour = currentHourSelected + hours;

            let realMinuteStr = realMiunute < 10 ? `0${realMiunute}` : `${realMiunute}`;
            let realMinuteInd = this.minusArr.indexOf(realMinuteStr);

            this.minsControl.setValue(realMinuteStr);
            this.minsInd = realMinuteInd;
            this.processHours(newHour);
          }
        }
      }
    });
  }

  processHours(specificValue: number){
    let cycles = Math.trunc(specificValue / 12);
    let period = cycles % 2 == 0 ? 'am' : 'pm';
    
    this.changePeriod(period);

    let overflowedHours = cycles * 12;
    let realHour = specificValue - overflowedHours;

    if(realHour <= 0 && period == 'pm'){
      realHour = 12;
    }

    let realHourStr = realHour < 10 ? `0${realHour}` : `${realHour}`;
    let realHourInd = this.hoursArr.indexOf(realHourStr);

    this.hourInd = realHourInd;
    this.hourControl.setValue(realHourStr);
  }
}
