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 { DataResponseGetIssueTracking, GetIssueTracking } from 'src/app/interfaces/acquisition-management/issue-tracking.interface';
import { IssureTrackingService } from 'src/app/services/acquisition-management/issure-tracking.service';
import { ResourcesService } from 'src/app/services/resources/resources.service';
import { DetailsIssueTrackingComponent } from './details-issue-tracking/details-issue-tracking.component';
import { ResolutionIssueTrackingComponent } from './resolution-issue-tracking/resolution-issue-tracking.component';
import { UsersProfilesService } from 'src/app/services/users-profiles.service';
import { SocketService } from 'src/app/services/socket.service';
import { UserConsultResponse } from 'src/app/interfaces/user.interface';
import { EncService } from 'src/app/services/enc/enc.service';
import { Router } from '@angular/router';
import { ProfileInterface } from 'src/app/interfaces/profile.interface';

@Component({
  selector: 'app-issue-tracking',
  templateUrl: './issue-tracking.component.html',
  styleUrls: ['./issue-tracking.component.css']
})
export class IssueTrackingComponent implements AfterViewInit, OnInit {

  public displayedColumns: Array<string>;
  public dataSource: MatTableDataSource<GetIssueTracking>;
  @ViewChild(MatPaginator) paginator!: MatPaginator;
  @ViewChild(MatSort) sort!: MatSort;

  public isLoading: boolean;
  public isLoadingForm: boolean;

  constructor(
    public resourcesService: ResourcesService,
    private _router: Router,
    private _dialog: MatDialog,
    private _encService: EncService,
    private _socketService: SocketService,
    private _usersProfilesSevice: UsersProfilesService,
    private _issureTrackingService: IssureTrackingService,
  ) {
    this.displayedColumns = [ 'SEPR_IDPR','DESP_NOMB','SEPR_TIPO','SEPR_NUOR',/* 'SEPR_DESC', */'SEPR_FEMO','SEPR_USMO','SEPR_ESTA','ACCIONES'];
    this.dataSource = new MatTableDataSource();
    this.isLoading = false;
    this.isLoadingForm = false;
  }

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

  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(parseInt(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}`);
            }
          }, ( httpErrorResponse: HttpErrorResponse ) => this.resourcesService.checkErrors(httpErrorResponse)
        );
      }
    });
  }

  // Se obtiene la información de los seguimientos de problemas
  public async getIssueTracking() {
    this.isLoading = true;
    await lastValueFrom(this._issureTrackingService.getIssueTracking()).then(
      (responseData: DataResponseGetIssueTracking) => {
        if (!responseData.error) {
          this.dataSource.data = responseData.response;
        } else {
          this.resourcesService.openSnackBar(responseData.msg);
        }
      }, (error: HttpErrorResponse) => this.resourcesService.checkErrors(error)
    );
    this.isLoading = false;
  }

  public openDialog(typeDialog: string, elementData: GetIssueTracking) {
    if (typeDialog === 'DETAILS') {
      this._dialog.open(DetailsIssueTrackingComponent, {
        width: '650px',
        disableClose: true,
        data: elementData,
      });
    } else if (typeDialog === 'RESOLUTION') {
      this._dialog.open(ResolutionIssueTrackingComponent, {
        width: '650px',
        disableClose: true,
        data: elementData,
      }).afterClosed().subscribe((result)=>{
        if(result){
          this.getIssueTracking();
        }
      });
    }
  }


}
