import { Component, Inject, OnInit } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog';
import { map, Observable, startWith } from 'rxjs';
import { ResourcesService } from '../../../services/resources.service';

@Component({
    selector: 'app-clock-select',
    templateUrl: './clock-select.component.html',
    styleUrl: './clock-select.component.css',
    standalone: false
})
export class ClockSelectComponent implements OnInit {
  public formGroup: FormGroup;
  public arrHours: Array<string>;
  public arrMinutes: Array<string>;

  public filteredHours!: Observable<Array<string>>;
  public filteredMinutes!: Observable<Array<string>>;
  
  constructor(  
    @Inject(MAT_DIALOG_DATA) public clock: string,
    public resourcesService: ResourcesService,
    private _dialogReg: MatDialogRef<string | boolean>,
  ){
    this.formGroup = this.createFormControl();

    this.arrHours = [];
    for (let hour = 0; hour <= 23; hour++) {
      this.arrHours.push( this.numberToString(hour) );
    }
    
    this.arrMinutes = [];
    for (let minute = 0; minute < 60; minute += 15) {
      this.arrMinutes.push( this.numberToString(minute) );
    }
  }
  
  private createFormControl() {
    return new FormGroup({
      'HORA': new FormControl('', [Validators.required, Validators.max(24), Validators.min(0) ]),
      'MINUTO': new FormControl('', [Validators.required, Validators.max(60), Validators.min(0) ]),
    })
  }

  private numberToString(digitNumber: number) {
    let newDigit: string = '';
    if (digitNumber < 10 && digitNumber >= 0) {
      newDigit = `0${digitNumber}`;
    } else {
      newDigit = `${digitNumber}`;
    }
    return newDigit;
  }
  
  ngOnInit() {
    this.getDataClock();

    this.filteredHours = this.formGroup.controls['HORA'].valueChanges.pipe(
      startWith(''),
      map((value) => {
        value = value === null || value === undefined ? '' : value;
        const filterValue: string = value.toString().toLowerCase();
        return this.arrHours.filter((element:string) => element.includes(filterValue));
      })
    );
    this.filteredMinutes = this.formGroup.controls['MINUTO'].valueChanges.pipe(
      startWith(''),
      map((value) => {
        value = value === null || value === undefined ? '' : value;
        const filterValue: string = value.toString().toLowerCase();
        return this.arrMinutes.filter( (element:string) => element.includes(filterValue));
      })
    );
  }

  private getDataClock() {
    if (this.clock === '') {
      return;
    }

    this.clock = this.clock.trim();
    let arrClock = this.clock.split(':');

    if (arrClock.length !== 2) {
      this.resourcesService.openSnackBar(`Ocurrió un error al leer el formato de la hora.`);
      this._dialogReg.close(false);
      return;
    }

    let hour: string = arrClock[0].toString().trim();
    let minute: string = arrClock[1].toString().trim();

    if (!this.arrHours.includes(hour)) {
      this.resourcesService.openSnackBar(`Ocurrió un error al leer el campo de la hora.`);
      this._dialogReg.close(false);
      return;
    }
    if (!this.arrMinutes.includes(minute)) {
      this.resourcesService.openSnackBar(`Ocurrió un error al leer el campo de los minutos.`);
      this._dialogReg.close(false);
      return;
    }

    this.formGroup.controls['HORA'].setValue(hour);
    this.formGroup.controls['MINUTO'].setValue(minute);

  }

  public save() {
    let hour: string = this.formGroup.controls['HORA'].value;
    hour = hour.toString().trim();
    let minute: string = this.formGroup.controls['MINUTO'].value;
    minute = minute.toString().trim();

    if (!this.arrHours.includes(hour)) {
      this.resourcesService.openSnackBar(`El campo Hora debe estar incluido en la lista de horas disponibles.`);
      return;
    }
    if (!this.arrMinutes.includes(minute)) {
      this.resourcesService.openSnackBar(`El campo Minuto debe estar incluido en la lista de mintuos disponibles.`);
      return;
    }

    let clock: string = `${hour}:${minute}`;
    this._dialogReg.close(clock);
  }
}
