import { Component, Inject, OnInit, ViewChild } from '@angular/core';
import { CatalogueResponse, CataloguesResponse } from '../../../interfaces/catalogues.interface';
import { MatTableDataSource } from '@angular/material/table';
import { MatPaginator } from '@angular/material/paginator';
import { MatSort } from '@angular/material/sort';
import { DOCUMENT } from '@angular/common';
import { CataloguesService } from '../../../services/catalogues.service';
import { MatDialog } from '@angular/material/dialog';
import { EncService } from '../../../services/enc.service';
import { Router } from '@angular/router';
import { FunctionsService } from '../../../services/functions.service';
import { SocketService } from '../../../services/socket.service';
import { UsersProfilesService } from '../../../services/users-profiles.service';
import { GdelService } from '../../../services/gdel.service';
import { ResourcesService } from '../../../services/resources.service';
import { UserConsultResponse } from '../../../interfaces/user.interface';
import { lastValueFrom } from 'rxjs';
import { ProfileInterface } from '../../../interfaces/profile.interface';
import { Permissions } from '../../../interfaces/permissions.interface';
import { UploadCatalogueComponent } from './upload-catalogue/upload-catalogue.component';
import { apiTemp } from '../../../../environments/environment.prod';
import { HistoryViewerComponent } from './history-viewer/history-viewer.component';

@Component({
    selector: 'app-catalogues',
    templateUrl: './catalogues.component.html',
    styleUrl: './catalogues.component.css',
    standalone: false
})
export class CataloguesComponent implements OnInit {
  isLoading: boolean;
  hasError: boolean;
  errorStr: string;
  catArr: CatalogueResponse[];
  downloadURI: string;
  downloadLink: string;

  displayedColumns: string[] = ['id', 'tipo', 'version', 'usuareg', 'fechareg', 'acciones'];
  dataSource?: MatTableDataSource<CatalogueResponse>;

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

  public btnSmall: boolean = false;
  public txtBuscador:string;

  cataloguesHistoryEnabled: boolean;
  newCatalogueEnabled: boolean;

  constructor(
    @Inject(DOCUMENT) private _document: Document,
    private _cataloguesService: CataloguesService,
    private _dialogUploader: MatDialog,
    private _encService: EncService,
    private _router: Router,
    private _functionsService: FunctionsService,
    private _socketService: SocketService,
    private _usersProfilesService: UsersProfilesService, 
    private _gdelService: GdelService,
    private _resourcesService: ResourcesService,
  ) { 
    this.isLoading = true;
    this.hasError = false;
    this.errorStr = "";
    this.catArr = [];
    this.downloadURI = "";
    this.downloadLink = "";
    this.txtBuscador = '';
    this.cataloguesHistoryEnabled = true;
    this.newCatalogueEnabled = true;
  }

  ngOnInit(): void {
    this.getData();
    this.onResize();
    this._socketService.refreshPermissions().subscribe(async (profUpdEnc) => {
      try{
        let idUser = localStorage.getItem('idusuario')!;
        let usrInfo: UserConsultResponse = await lastValueFrom(this._usersProfilesService.getUser(idUser, idUser, 1));
        
        if(usrInfo.error){
          this._resourcesService.openSnackBar('ERR_NPE000: Ocurrió un error inesperado.');
        }else{
          let idProfDec = await this._encService.decrypt(usrInfo.response.PERFIL);
          let currentProfile = await this._encService.decrypt(localStorage.getItem('perfil')!);

          if(idProfDec != currentProfile){
            this._router.navigate(['/sam/home']);
            return;
          }
          
          let profileUpdated = await this._encService.decrypt(`${profUpdEnc}`);
          if(profileUpdated == currentProfile){
            let profile = localStorage.getItem('perfil')!;
            let profInfo: ProfileInterface = await lastValueFrom(this._usersProfilesService.getProfile(
              profile,
              idUser,
              1
            ));

            let permArr = await this._functionsService.processPermissions(profInfo.response.PERMISOS.permissions);
            let modPerm = permArr.filter(item => item.id == 'S002V01M01ADSI');
            if(modPerm.length > 0){
              let funPerm = modPerm[0].children.filter(item => item.id == 'S002V01F10AGCA');
              if(funPerm.length > 0){
                let cataloguesHistoryEnabled = funPerm[0].children.filter(item => item.id == 'S002V01P01HICA');
                if(cataloguesHistoryEnabled.length){
                  this.cataloguesHistoryEnabled = cataloguesHistoryEnabled[0].access > 0;
                }

                let newCatalogueEnabled = funPerm[0].children.filter(item => item.id == 'S002V01P02NUCA');
                if(newCatalogueEnabled.length > 0){
                  this.newCatalogueEnabled = newCatalogueEnabled[0].access > 0;
                }
              }
            }
          }
        }
      }catch(error: any){
        if(error.error == undefined){
          this._resourcesService.openSnackBar('ERR_PAD001: Ocurrió un error inesperado.');
        }else if(error.error.msg == undefined){
          this._resourcesService.openSnackBar('ERR_PAD002: Ocurrió un error inesperado.');
        }else{
          this._resourcesService.openSnackBar(`ERR_PAD003: ${error.error.msg}`);
        }
      }
    });
  }

  async getData(){
    try{
      this.isLoading = true;
      this.hasError = false;
      this.errorStr = "";
      this.catArr = [];
      
      let idEnc = localStorage.getItem('idusuario')!;
      let catalogues: CataloguesResponse = await lastValueFrom(this._cataloguesService.getCatalogues(idEnc, 1));
      
      catalogues.response.forEach(item => {
        this.catArr.push(item);
      });

      this.dataSource = new MatTableDataSource(this.catArr);
      this.dataSource.paginator = this.paginator!;
      this.dataSource.sort = this.sort!;

      let permissionsEnc = localStorage.getItem('permisos');
      let permissionsDec = await this._encService.decrypt(permissionsEnc!);
      let permissionsArr: Permissions = JSON.parse(permissionsDec);

      let modPerm = permissionsArr.permissions.filter(item => item.id == 'S002V01M01ADSI')[0];
      let funPerm = modPerm.children.filter(item => item.id == 'S002V01F10AGCA')[0];

      this.cataloguesHistoryEnabled = funPerm.children.filter(item => item.id == 'S002V01P01HICA')[0].access > 0;
      this.newCatalogueEnabled = funPerm.children.filter(item => item.id == 'S002V01P02NUCA')[0].access > 0;

      this.isLoading = false;
    }catch(error: any){
      this.isLoading = false;
      this.hasError = true;
      this.errorStr = error.error.msg;
    }
  }

  public onResize():void {
    this.btnSmall = window.innerWidth <= 1405;
  }

  applyFilter(event: any, type: string){
    let filterValue:string;
    if (type == 'INP') {
      filterValue = (event.target as HTMLInputElement).value;
    }else{
      this.txtBuscador = event;
      filterValue = event;
    }
    this.dataSource!.filter = filterValue.trim().toLowerCase();

    if(this.dataSource?.paginator){
      this.dataSource.paginator.firstPage();
    }
  }

  openUploader(){
    const dialogRef = this._dialogUploader.open(UploadCatalogueComponent, {
      disableClose: true
    });

    dialogRef.afterClosed().subscribe(result => {
      if(result == true){
        this.catArr = [];
        this.isLoading = true;
        this.getData();
      }
    })
  }

  orderDate(date: string): string{
    return this._functionsService.orderDate(date)!;
  }

  async downloadCatalogue(attached: string){
    try{
      let download = this._document.getElementById('download') as HTMLAnchorElement;
      let attachedArr = JSON.parse(attached);
      let fileEnc = attachedArr[0];
      let idEnc = localStorage.getItem('idusuario')!;

      let downloadToken = await lastValueFrom(this._gdelService.getDownloadToken(fileEnc, idEnc, 1));
      
      download.href = `${apiTemp}download-file/${downloadToken.response.TOKEN}/${idEnc}/1`;
      download.download = "";
      download.click();
    }catch(error: any){
      let msg = "";
      if(error.error == undefined){
        msg = 'Ocurrió un error inesperado';
      }else if(error.error.msg == undefined){
        msg = 'Ocurrió un error inesperado';
      }else{
        msg = error.error.msg;
      }

      this._resourcesService.openSnackBar(msg);
    }
  }

  async openViewer(attached: string){
    try{
      let attachedArr = JSON.parse(attached);
      let id = attachedArr[0];
      
      this._router.navigate(['sam/ADSI/AGCA/lector'], {
        queryParams: {
          info: id
        }
      });
    }catch(error: any){
      let msg = "";

      if(error.error == undefined){
        msg = 'Ocurrió un error inesperado.';
      }else if(error.error.msg == undefined){
        msg = 'Ocurrió un error inesperado.';
      }else{
        msg = error.error.msg;
      }

      this._resourcesService.openSnackBar(msg);
    }
  }

  openHistory(type: string){
    let dialogRef = this._dialogUploader.open(HistoryViewerComponent, {
      width: '720px',
      data: {
        type: type,
      }
    });

    dialogRef.afterClosed().subscribe(res => {
      if(res != undefined && res != null && res != ""){
        let resArr = res.split("|");
        let fileStr = resArr[0];
        let action = resArr[1];

        if(action == 'download'){
          this.downloadCatalogue(fileStr);
        }else if(action == 'open'){
          this.openViewer(fileStr);
        }else{
          this._resourcesService.openSnackBar('Nose encontró la acción solicitada.');
        }
      }
    });
  }

  openCatalogueAdmin(type: string){
    this._router.navigate(['sam/ADSI/AGCA/adminstrar'], {
      queryParams: {
        type: type,
      },
    })
  }
}
