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

@Component({
  selector: 'app-symptom-list',
  templateUrl: './symptom-list.component.html',
  styleUrls: ['./symptom-list.component.css']
})
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 _symptomService: SymptomListService,
  ) {
    this.dataSource = new MatTableDataSource<MatTableSymptomList>();
    this.displayedColumns = [
      'ID_SINTOMA',
      'NOMBRE_SINTOMA',
      'CAUSA',
      'CLASIFICACION',
      'LIMITE_VALOR',
      'USUARIO_REGISTRA',
      'FECHA_REGISTRA',
      '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;
    let idUser = localStorage.getItem('idusuario')!;
    await lastValueFrom(this._symptomService.getSymptom(idUser)).then(
      async (responseData: ResponseDataGetSymptomList) => {
        if ( !responseData.error ) {
          let arrSymptoms:Array<MatTableSymptomList> = [];
          await Promise.all(
            responseData.response.map((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_REGISTRA: this.resourcesService.selectUser(symptomList.USUARIO_REGISTRA, symptomList.USUARIO_MODIFICA),
                FECHA_REGISTRA: this.resourcesService.formatDate(symptomList.FECHA_REGISTRA, symptomList.FECHA_MODIFICA),
                ESTADO: symptomList.ESTADO,
              })
            })
          );

          this.dataSource.data = arrSymptoms;
          
        } else {
          this.resourcesService.openSnackBar(`${responseData.msg}`);
        }
      }, (error: HttpErrorResponse) => this.resourcesService.checkErrors(error)
    );
    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._symptomService.deteleSymptom(requestDataDelete)).then(
      (responseData: ResponseData) => {
        if ( !responseData.error ) {
          this.resourcesService.openSnackBar(`¡Eliminación Exitosa!`);
          this.getSymptoms();
        } else {
          this.resourcesService.openSnackBar(`${responseData.msg}`);
        }
      }, (httpErrorResponse: HttpErrorResponse) => this.resourcesService.checkErrors( httpErrorResponse )
    );
    this.isLoadingForm = false;
  }
}
