import { AfterViewInit, Component, OnInit, ViewChild } from '@angular/core';
import { MatPaginator } from '@angular/material/paginator';
import { MatSort } from '@angular/material/sort';
import { MatTableDataSource } from '@angular/material/table';
import { ResourcesService } from '../../../../services/resources.service';
import { Router } from '@angular/router';
import { EncService } from '../../../../services/enc.service';
import { SocketService } from '../../../../services/socket.service';
import { UsersProfilesService } from '../../../../services/users-profiles.service';
import { DispatchService } from '../../../../services/acquisition-management/dispatch.service';
import { UserConsultResponse } from '../../../../interfaces/user.interface';
import { lastValueFrom } from 'rxjs';
import { ProfileInterface } from '../../../../interfaces/profile.interface';
import { HttpErrorResponse } from '@angular/common/http';
import { ResponseDataGetDelayAnalysis } from '../../../../interfaces/acquisition-management/delay-analysis.interface';
import { FunctionsService } from '../../../../services/functions.service';

const ID_MODULE = "S002V01M05GEAD";
@Component({
    selector: 'app-delay-analysis',
    templateUrl: './delay-analysis.component.html',
    styleUrl: './delay-analysis.component.css',
    standalone: false
})
export class DelayAnalysisComponent implements AfterViewInit, OnInit {
  @ViewChild(MatPaginator) paginator!: MatPaginator;
  @ViewChild(MatSort) sort!: MatSort;
  public displayedColumns: Array<string>;
  public dataSource: MatTableDataSource<any>;

  public isLoading: boolean;
  public isLoadingForm: boolean;

  constructor(
    public resourcesService: ResourcesService,
    private _router: Router,
    private _encService: EncService,
    private _socketService: SocketService,
    private _usersProfilesSevice: UsersProfilesService,
    private _dispatchService: DispatchService,
    private _functionsService: FunctionsService,
  ) {
    this._functionsService.consultModuleStatus(ID_MODULE);
    this.displayedColumns = [ 'ANRE_IDAR', 'ANRE_NUOR', 'PROV_NUPR', 'ANRE_FEMO', 'ANRE_ESTA', 'ACCIONES' ];
    this.dataSource = new MatTableDataSource();
    this.isLoading = false;
    this.isLoadingForm = false;
  }

  async ngOnInit() {
    await this.refreshPermissions();
    await this.getDelayAnalysis();
  }

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

  private async refreshPermissions() {
    this._socketService.refreshPermissions().subscribe(async (profUpdEnc) => {
      let idUser = localStorage.getItem('idusuario')!;
      let usrInfo: UserConsultResponse = await lastValueFrom(this._usersProfilesSevice.getUser(idUser, idUser, 1));
      let currentProfile = await this._encService.decrypt(localStorage.getItem('perfil')!);

      if(currentProfile != usrInfo.response.PERFIL){
        this._router.navigate(['/sam/home']);
      }

      let profileUpdated = await this._encService.decrypt(`${profUpdEnc}`);
      if(profileUpdated == currentProfile){
        let profile = localStorage.getItem('perfil')!;

        await lastValueFrom(this._usersProfilesSevice.getProfile( profile, idUser, 1 )).then(
          (responseData: ProfileInterface) => {
            if (!responseData.error) {
              let modPerm = responseData.response.PERMISOS.permissions.filter(item => item.id == 'S002V01M05GEAD')[0];
              let funPerm = modPerm.children.filter(item => item.id == 'S002V03S03DESP')[0];
              let panPerm = funPerm.children.filter(item => item.id == "S002V01F04ANRE")[0];

              if (panPerm.access === 0) {
                this._router.navigate(['/sam/home']);
              }

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

    this._socketService.refreshModules().subscribe(async () => this._functionsService.consultModuleStatus(ID_MODULE));
  }

  public async getDelayAnalysis() {
    this.isLoading = true;
    const user: string = this.resourcesService.getUser();
    const line: number = this.resourcesService.getLineNumber();
    await lastValueFrom(this._dispatchService.getDelayAnalysis(user, line)).then(
      (responseData: ResponseDataGetDelayAnalysis) => {
        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.getDelayAnalysis();
        }
      }
    );
    this.isLoading = false;
  }
}
