import { HttpErrorResponse } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';
import { MatDialog } from '@angular/material/dialog';
import { MatTableDataSource } from '@angular/material/table';
import { lastValueFrom } from 'rxjs';
import { CatalogMeasures, ResponseDataGet } from 'src/app/interfaces/ANFA/catalog-measures.interface';
import { ResponseData } from 'src/app/interfaces/response-data';
import { CatalogMeasuresService } from 'src/app/services/failure-analysis/catalog-measures.service';
import { ResourcesService } from 'src/app/services/resources/resources.service';
import { AlertComponent } from '../../resources/dialogs/alert/alert.component';
import { MeasuresFormComponent } from './measures-form/measures-form.component';

@Component({
  selector: 'app-catalog-measures',
  templateUrl: './catalog-measures.component.html',
  styleUrls: ['./catalog-measures.component.css']
})
export class CatalogMeasuresComponent implements OnInit {

  public txtBuscador:string;

  public isLoading: boolean;
  public isLoadingForm: boolean;
  public btnSmall: boolean;

  public dataSource: MatTableDataSource<any>;
  public displayedColumns: Array<string>;

  constructor(
    public resourcesService: ResourcesService,
    private _catalogMeasureService: CatalogMeasuresService,
    private _dialog: MatDialog,
  ) {
    this.txtBuscador = '';

    this.isLoading = false;
    this.isLoadingForm = false;
    this.btnSmall = false;

    this.dataSource = new MatTableDataSource<any>();
    this.displayedColumns = ['LIME_IDME','LIME_MEDI','LIME_ACRO','LIME_USRE','LIME_FERE','LIME_ESTA','ACTIONS'];
  }

  ngOnInit(): void {
    this.getCatalogMeasures();
  }

  public async getCatalogMeasures() {
    await lastValueFrom(this._catalogMeasureService.getCatalogMeasures()).then(
      (responseData: ResponseDataGet) => {
        this.dataSource.data = responseData.response;
      }, (error: HttpErrorResponse) => this.resourcesService.checkErrors(error)
    );
  }

  // Método de filtrado de datos
  public applyFilter(event: any, type: string):void {
    let filterValue:string;
    if (type == 'INP') {
      filterValue = (event.target as HTMLInputElement).value;
    }else{
      this.txtBuscador = event;
      filterValue = event;
    }
    this.dataSource.filter = filterValue.trim().toLowerCase();
    if (this.dataSource.paginator) {
      this.dataSource.paginator.firstPage();
    }
  }

  public openDialog( typeForm: string, element?:CatalogMeasures ) {
    if ( typeForm === 'REG' || typeForm === 'UPD' ) {
      this._dialog.open( MeasuresFormComponent, {
        width: '800px',
        disableClose: true,
        data: { action: typeForm, dataElement: element },
      }).afterClosed().subscribe((result) => {
        if (result === 'EXITO') {
          this.getCatalogMeasures();
        }
      });
    } else if ( typeForm === 'DEL' ) {
      this._dialog.open( AlertComponent, {
        data: {
          title: 'Eliminación de Falla',
          description: '¿Está seguro que desea eliminar la falla?',
          icon: 'warning',
        },
        disableClose: true,
      }).afterClosed().subscribe((result) => {
        if (result) {
          this.deleteCatalogMeasures(element!.LIME_IDME);
        }
      });
    }
  }

  private async deleteCatalogMeasures(idMeasure: number) {
    await lastValueFrom(this._catalogMeasureService.deleteCatalogMeasures({
      ID_MEDIDA: idMeasure,
      NUMERO_LINEA: 1,
      USUARIO: this.resourcesService.getUser()
    })).then(
      (responseData: ResponseData) => {
        this.resourcesService.openSnackBar('¡Eliminación Exitosa!');
        this.getCatalogMeasures();
      }, (error: HttpErrorResponse) => this.resourcesService.checkErrors(error)
    );
  }

  // Método para reajustar los botones según sus dimensiones
  public onResize():void {
    this.btnSmall = window.innerWidth <= 1405;
  }

}
