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

@Component({
  selector: 'app-catalogues',
  templateUrl: './catalogues.component.html',
  styleUrls: ['./catalogues.component.css']
})
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 _snackBar: MatSnackBar,
    private _router: Router,
    private _functionsService: FunctionsService,
    private _advicesService: AdvicesService,
    private _socketService: SocketService,
    private _usersProfilesSevice: UsersProfilesService, 
    private _gdelService: GdelService,
  ) { 
    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) => {
      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){
        try{
          let profile = localStorage.getItem('perfil')!;
          let profInfo: ProfileInterface = await lastValueFrom(this._usersProfilesSevice.getProfile(
            profile,
            idUser,
            1
          ));

          let modPerm = profInfo.response.PERMISOS.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;
        }catch(error: any){
          if(error.error == undefined){
            this.openSnackBar('Ocurrió un error al actualizar su perfil');
          }else if(error.error.msg == undefined){
            this.openSnackBar('Ocurrió un error al actualizar su perfil');
          }else{
            this.openSnackBar(error.error.msg);
          }
        }
      }
    });
  }

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

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

  openSnackBar(msg: string){
    this._snackBar.open(msg, 'Cerrar', {
      duration: 5000
    })
  }

  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;
    }
  }

  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')!;
      console.log(fileEnc);

      let downloadToken = await lastValueFrom(this._gdelService.getDownloadToken(fileEnc, idEnc, 1));
      
      download.href = `http://git.ittec.mx/sam/public/api/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.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.openSnackBar(msg);
    }
  }

  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();
    }
  }

  goBack(steps: number){
    window.history.go(steps * -1);
  }

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

  openHistory(type: string){
    let dialogRef = this._dialogUploader.open(HistoryViewerComponent, {
      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.openSnackBar('Nose encontró la acción solicitada.');
        }
      }
    });
  }

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

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