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

@Component({
    selector: 'app-hour-selector',
    templateUrl: './hour-selector.component.html',
    styleUrl: './hour-selector.component.css',
    standalone: false
})
export class HourSelectorComponent implements OnInit {
  hoursControl: FormControl;
  minutesControl: FormControl;

  constructor(
    @Inject(MAT_DIALOG_DATA) private _data: any,
    private _dialogRef: MatDialogRef<HourSelectorComponent>,
  ){
    this.hoursControl = new FormControl(0);
    this.minutesControl = new FormControl(0);
  }

  ngOnInit(): void {
    let valueNum = parseFloat(this._data.value);
    let hours = Math.trunc(valueNum);
    this.hoursControl.setValue(hours);

    let minutesFloat = valueNum - hours;
    let minutesInt = Math.round(minutesFloat * 60);
    this.minutesControl.setValue(minutesInt);
  }

  verifyNumber(input: string, value: string){
    let validChars = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];
    let valueArr = value.split('');
    let validVal = '';

    for(const char of valueArr){
      if(validChars.includes(char)){
        validVal += char;
      }
    }

    let valueNum = isNaN(parseInt(validVal)) ? 0 : parseInt(validVal);
    if(input == 'hours'){
      this.hoursControl.setValue(valueNum);
    }else if(input == 'minutes'){
      if(valueNum > 59){
        this.minutesControl.setValue(59);
      }else{
        this.minutesControl.setValue(valueNum);
      }
    }
  }

  changeHours(action: string){
    let currentVal = this.hoursControl.value;
    let newVal = 0;

    if(action == 'add'){
      newVal = currentVal + 1;
    }else if(action == 'rem'){
      newVal = currentVal - 1;
    }

    if(newVal < 0){
      this.hoursControl.setValue(0);
    }else if(newVal > 59){
      this.hoursControl.setValue(59);
    }else{
      this.hoursControl.setValue(newVal);
    }
  }

  changeMinutes(action: string){
    let currentVal = this.minutesControl.value;
    let newVal = 0;

    if(action == 'add'){
      newVal = currentVal + 1;
    }else if(action == 'rem'){
      newVal = currentVal - 1;
    }

    if(newVal < 0){
      this.minutesControl.setValue(0);
    }else if(newVal > 59){
      this.minutesControl.setValue(59);
    }else{
      this.minutesControl.setValue(newVal);
    }
  }

  close(){
    let data = `${this.hoursControl.value}|${this.minutesControl.value}`;
    this._dialogRef.close(data);
  }
}
