import { Component, OnInit, ViewChild } from '@angular/core';
import { MatTableDataSource } from '@angular/material/table';
import { AlarmEmissionFromFailures, ResponseDataGetAlarmEmissionFromFailures } from '../../../interfaces/failure-analysis/failure.interface';
import { ResourcesService } from '../../../services/resources.service';
import { FailureAnalysisService } from '../../../services/failure-analysis/failure-analysis.service';
import { lastValueFrom } from 'rxjs';
import { HttpErrorResponse } from '@angular/common/http';
import { MatPaginator } from '@angular/material/paginator';
import { MatSort } from '@angular/material/sort';

@Component({
    selector: 'app-alarm-emission',
    templateUrl: './alarm-emission.component.html',
    styleUrl: './alarm-emission.component.css',
    standalone: false
})
export class AlarmEmissionComponent implements OnInit {
  public isLoading: boolean;
  public dataSource: MatTableDataSource<AlarmEmissionFromFailures>;
  public displayedColumns: Array<string>;
  
  @ViewChild(MatPaginator) paginator!: MatPaginator;
  @ViewChild(MatSort) sort!: MatSort;
  
  constructor(
    public resourcesService: ResourcesService,
    private _failureAnalysisService: FailureAnalysisService,
  ) {
    this.dataSource = new MatTableDataSource<AlarmEmissionFromFailures>();
    this.displayedColumns = [
      'NUMERO_FALLA',
      'CODIGO_EQUIPAMIENTO',
      'ID_ACTIVADOR',
      'FECHA_FALLA',
      'PRIORIDAD',
      'TIPO_ACTIVADOR',
    ];
    this.isLoading = false;
  }
  
  async ngOnInit() {
    this.isLoading = true;
    await this.getAlarmEmissionFromFailures()
    this.isLoading = false;
  }

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