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

@Component({
  selector: 'app-time-picker',
  templateUrl: './time-picker.component.html',
  styleUrls: ['./time-picker.component.css']
})
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(private _dialogRef: MatDialogRef<TimePickerComponent>) { 
    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}`);
      }
    }

    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 = this.hoursArr.length - 1;
      }else{
        this.hourInd++;
      }
    }else{
      let indAux = this.hourInd - 1;
      if(indAux <= 0){
        this.hourInd = 0;
      }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 = this.minusArr.length - 1;
      }else{
        this.minsInd++;
      }
    }else{
      let indAux = this.minsInd - 1;
      if(indAux <= 0){
        this.minsInd = 0;
      }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);
  }
}
