import { AfterViewInit, Component, OnInit, ViewChild } from '@angular/core';
import { MatTableDataSource } from '@angular/material/table';
import { MatTableSymptomList, RequestDataDeleteSymtom, ResponseDataGetSymptomList, SymptomList } from '../../../interfaces/failure-analysis/symptom.interface';
import { MatPaginator } from '@angular/material/paginator';
import { MatSort } from '@angular/material/sort';
import { ResourcesService, ResponseData } from '../../../services/resources.service';
import { MatDialog } from '@angular/material/dialog';
import { Router } from '@angular/router';
import { EncService } from '../../../services/enc.service';
import { FailureAnalysisService } from '../../../services/failure-analysis/failure-analysis.service';
import { lastValueFrom } from 'rxjs';
import { HttpErrorResponse } from '@angular/common/http';
import { AlertComponent } from '../../resources/dialogs/alert/alert.component';

@Component({
    selector: 'app-symptom-list',
    templateUrl: './symptom-list.component.html',
    styleUrl: './symptom-list.component.css',
    standalone: false
})
export class SymptomListComponent implements OnInit, AfterViewInit {
  public isLoading: boolean;
  public isLoadingForm: boolean;

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

  @ViewChild(MatPaginator) paginator!: MatPaginator;
  @ViewChild(MatSort) sort!: MatSort;

  constructor(
    public resourcesService: ResourcesService,
    private _dialog: MatDialog,
    private _router: Router,
    private _encService: EncService,
    private _failureAnalysisService: FailureAnalysisService,
  ) {
    this.dataSource = new MatTableDataSource<MatTableSymptomList>();
    this.displayedColumns = [
      'ID_SINTOMA',
      'NOMBRE_SINTOMA',
      'CAUSA',
      'CLASIFICACION',
      'LIMITE_VALOR',
      'USUARIO_MODIFICA',
      'FECHA_MODIFICA',
      'ESTADO',
      'ACTIONS'
    ];
    this.isLoading = false;
    this.isLoadingForm = false;
  }

  ngOnInit(): void {
    this.isLoading = true;
    this.getSymptoms();
    this.isLoading = false;
  }

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

  public async getSymptoms() {
    this.isLoading = true;
    const user: string = this.resourcesService.getUser();
    const line: number = this.resourcesService.getLineNumber();
    await lastValueFrom(this._failureAnalysisService.getSymptom(user, line)).then(
      async (responseData: ResponseDataGetSymptomList) => {
        if ( !responseData.error ) {
          let arrSymptoms:Array<MatTableSymptomList> = [];
          await Promise.all(
            responseData.response.map(async (symptomList:SymptomList) => {
              arrSymptoms.push({
                ID_SINTOMA: symptomList.ID_SINTOMA,
                NOMBRE_SINTOMA: symptomList.NOMBRE_SINTOMA,
                CAUSA: symptomList.CAUSA,
                CLASIFICACION: symptomList.CLASIFICACION,
                LIMITE_VALOR: `${symptomList.LIMITE_VALOR} ${symptomList.ACRONIMO_MEDIDA}`,
                USUARIO_MODIFICA: symptomList.USUARIO_MODIFICA,
                FECHA_MODIFICA: symptomList.FECHA_MODIFICA,
                ESTADO: symptomList.ESTADO,
              })
            })
          );

          this.dataSource.data = arrSymptoms;
          
        } else {
          this.resourcesService.openSnackBar(`${responseData.msg}`);
        }
      }, async (httpErrorResponse: HttpErrorResponse) => {
        let response = this.resourcesService.checkErrors(httpErrorResponse)
        if (response !== null && response.reload) {
          await this.getSymptoms();
        }
      }
    );
    this.isLoading = false;
  }

  public async openForm(typeDialog: string, symptomList?: MatTableSymptomList ) {
    let idSymptomList = null;
    if (typeDialog === 'UPD' && symptomList !== undefined) {
      idSymptomList = symptomList.ID_SINTOMA;
    }

    let dataForm = { type: typeDialog, idSymptomList: idSymptomList }
    let strDataForm = JSON.stringify(dataForm);
    let encDataForm = await this._encService.encrypt(strDataForm);

    this._router.navigate([`/sam/ANFA/CLSI/${encDataForm}`]);
  }

  public async alert(symptomList:MatTableSymptomList) {
    this._dialog.open(AlertComponent, {
      disableClose: true,
      data: {
        title: `Eliminar Síntoma`,
        description: `¿Está seguro de eliminar el síntoma #${symptomList.ID_SINTOMA}?`,
        icon: `warning`
      }
    }).afterClosed().subscribe((result:boolean) => {
      if (result) {
        this.deleteSymptom(symptomList.ID_SINTOMA.toString());
      }
    })
  }

  private async deleteSymptom(idSymptom: string) {
    this.isLoadingForm = true;
    const requestDataDelete: RequestDataDeleteSymtom = {
      ID_SINTOMA: idSymptom,
      NUMERO_LINEA: this.resourcesService.getLineNumber(),
      USUARIO: this.resourcesService.getUser()
    }
    await lastValueFrom(this._failureAnalysisService.deteleSymptom(requestDataDelete)).then(
      (responseData: ResponseData) => {
        if ( !responseData.error ) {
          this.resourcesService.openSnackBar(`¡Eliminación Exitosa!`);
          this.getSymptoms();
        } else {
          this.resourcesService.openSnackBar(`${responseData.msg}`);
        }
      }, async (httpErrorResponse: HttpErrorResponse) => {
        let response = this.resourcesService.checkErrors(httpErrorResponse)
        if (response !== null && response.reload) {
          await this.deleteSymptom(idSymptom);
        }
      }
    );
    this.isLoadingForm = false;
  }
}
