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

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

  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,
  ) { 
    this.isLoading = true;
    this.hasError = false;
    this.errorStr = "";
    this.catArr = [];
    this.downloadURI = "";
    this.downloadLink = "";
    this.txtBuscador = '';
  }

  ngOnInit(): void {
    this.getData();
  }

  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 idShort = await lastValueFrom(this._encService.shortEncrypt(idEnc!));
      
      let catalogues: CataloguesResponse = await lastValueFrom(this._cataloguesService.getCatalogues(idShort.response.encrypted, 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!;

      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 shortFile = await lastValueFrom(this._encService.shortEncrypt(fileEnc));

      let idEnc = localStorage.getItem('idusuario');
      let shortEnc = await lastValueFrom(this._encService.shortEncrypt(idEnc!));

      let downloadToken = await lastValueFrom(this._advicesService.getDownloadToken(shortFile.response.encrypted, shortEnc.response.encrypted, 1));
      //this.downloadLink = `http://git.ittec.mx/sam/public/api/download-file/${downloadToken.response.TOKEN}/${shortEnc.response.encrypted}/1`;
      
      download.href = `http://git.ittec.mx/sam/public/api/download-file/${downloadToken.response.TOKEN}/${shortEnc.response.encrypted}/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];
      let idShort = await lastValueFrom(this._encService.shortEncrypt(id));
      
      this._router.navigate(['sam/ADSI/AGCA/lector'], {
        queryParams: {
          info: idShort.response.encrypted
        }
      });
    }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;
  }
}
