import { AfterViewInit, Component, OnInit, ViewChild } from '@angular/core';
import { MatTableDataSource } from '@angular/material/table';
import { CatalogFailure, ResponseDataGetCatalogFailure } from '../../../interfaces/failure-analysis/catalog-failure.interface';
import { MatPaginator } from '@angular/material/paginator';
import { MatSort } from '@angular/material/sort';
import { ResourcesService, ResponseData } from '../../../services/resources.service';
import { FailureAnalysisService } from '../../../services/failure-analysis/failure-analysis.service';
import { MatDialog } from '@angular/material/dialog';
import { lastValueFrom } from 'rxjs';
import { HttpErrorResponse } from '@angular/common/http';
import { FailureListFormComponent } from './failure-list-form/failure-list-form.component';
import { AlertComponent } from '../../resources/dialogs/alert/alert.component';

@Component({
    selector: 'app-failure-list',
    templateUrl: './failure-list.component.html',
    styleUrl: './failure-list.component.css',
    standalone: false
})
export class FailureListComponent implements OnInit, AfterViewInit {
  public isLoading: boolean;
  public dataSource: MatTableDataSource<CatalogFailure>;
  public displayedColumns: Array<string>;
  @ViewChild(MatPaginator) paginator!: MatPaginator;
  @ViewChild(MatSort) sort!: MatSort;

  constructor(
    public resourcesService: ResourcesService,
    private _failureAnalysisService: FailureAnalysisService,
    private _dialog: MatDialog,
  ) {
    this.isLoading = false;

    this.dataSource = new MatTableDataSource<CatalogFailure>();
    this.displayedColumns = ['ID_FALLA','NOMBRE_FALLA','NIVEL_CRITICIDAD','CAUSA_FALLA','USUARIO_MODIFICA','FECHA_MODIFICA','ESTADO','ACTIONS'];
  }

  ngAfterViewInit(): void {
    this.dataSource.paginator = this.paginator;
    this.dataSource.sort = this.sort;
  }

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

  public async getCatalogFailure() {
    this.isLoading = true;
    const user: string = this.resourcesService.getUser();
    const line: number = this.resourcesService.getLineNumber();
    await lastValueFrom(this._failureAnalysisService.getCatalogFailure(user, line)).then(
      (responseData: ResponseDataGetCatalogFailure) => {
        if ( !responseData.error ) { 
          this.dataSource.data = responseData.response;
        } else {
          this.resourcesService.openSnackBar(`${responseData.msg}`);
        }
      }, async (httpErrorResponse: HttpErrorResponse) => {
        let response = this.resourcesService.checkErrors(httpErrorResponse)
        if (response !== null && response.reload) {
          await this.getCatalogFailure();
        }
      }
    );
    this.isLoading = false;
  }

  public openDialog( typeForm: string, element?:CatalogFailure ) {
    if ( typeForm === 'REG' || typeForm === 'UPD' ) {

      let idCatalogFailure = null;
      if (typeForm === 'UPD' && element !== undefined) {
        idCatalogFailure = element.ID_FALLA;
      }
      this._dialog.open( FailureListFormComponent, {
        width: '1000px',
        maxWidth: '1000px',
        disableClose: true,
        data: { 
          type: typeForm, 
          idCatalogFailure: idCatalogFailure 
        },
      }).afterClosed().subscribe((result) => {
        if (result) {
          this.getCatalogFailure();
        }
      });
    } else if ( typeForm === 'DEL' && element !== undefined) {
      let failure: string = element.NOMBRE_FALLA;
      failure = failure.trim();
      
      this._dialog.open( AlertComponent, {
        data: {
          title: 'Eliminación de Falla',
          description: `¿Está seguro que desea eliminar la falla ${element.NOMBRE_FALLA}?`,
          icon: 'warning',
        },
        disableClose: true,
      }).afterClosed().subscribe((result) => {
        if (result) {
          this.deleteCatalogFailure(element);
        }
      });
    }
  }

  private async deleteCatalogFailure( catalogFailure: CatalogFailure ) {
    await lastValueFrom(this._failureAnalysisService.deleteCatalogFailure({
      ID_FALLA: catalogFailure.ID_FALLA,
      NUMERO_LINEA: this.resourcesService.getLineNumber(),
      USUARIO: this.resourcesService.getUser()
    })).then(
      (responseData: ResponseData) => {
        if ( !responseData.error ) {
          this.resourcesService.openSnackBar('¡Eliminación Exitosa!');
          this.getCatalogFailure();
        } else {
          this.resourcesService.openSnackBar(`${ responseData.msg }`)
        }
      }, async (httpErrorResponse: HttpErrorResponse) => {
        let response = this.resourcesService.checkErrors(httpErrorResponse)
        if (response !== null && response.reload) {
          await this.deleteCatalogFailure(catalogFailure);
        }
      }
    );
  }
}
