import { HttpErrorResponse } from '@angular/common/http';
import {
  Component,
  ViewChild,
  OnInit,
  AfterViewInit,
  ElementRef,
} 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 { Router } from '@angular/router';
import { AlertComponent } from 'src/app/components/resources/dialogs/alert/alert.component';
import { AlertData } from 'src/app/interfaces/alert.interface';
import { EncService } from 'src/app/services/enc/enc.service';
import { ResourcesService } from 'src/app/services/resources/resources.service';
import { lastValueFrom } from 'rxjs';

import WebViewer from '@pdftron/webviewer';
import { WebviewerComponent } from './webviewer/webviewer.component';
import { DocumentManagementService } from 'src/app/services/gdel/document-management.service';
import { MatSnackBar } from '@angular/material/snack-bar';
import { GdelService } from 'src/app/services/gdel/gdel.service';
@Component({
  selector: 'app-gdel',
  templateUrl: './gdel.component.html',
  styleUrls: ['./gdel.component.css'],
})
export class GDELComponent implements AfterViewInit, OnInit {
  @ViewChild('viewer') viewRef: any;
  public displayedColumns: Array<string>;
  public dataSource: MatTableDataSource<any>;
  @ViewChild(MatPaginator) paginator!: MatPaginator;
  @ViewChild(MatSort) sort!: MatSort;

  public isLoading: boolean;
  public isLoadingForm: boolean;
  public active: number = 0;
  public btnSmall: boolean;
  public ulOptSmall: boolean;
  public txtBuscador: string;
  public clickedIndex: any = 0;
  public options = [
    {
      id: 1,
      items: 'Mis documentos',
      icon: 'local_library',
    },
    {
      id: 2,
      items: 'Compartidos conmigo',
      icon: 'group_add',
    },
    {
      id: 3,
      items: 'Papelera',
      icon: 'delete',
    },
  ];
  public documents: Array<any> = [];
  constructor(
    private _encService: EncService,
    private _resourcesServices: ResourcesService,
    private _dialog: MatDialog,
    private _router: Router,
    public dialog: MatDialog,
    private _documentManagement: DocumentManagementService,
    private _gdelService: GdelService,
    private _snackBar: MatSnackBar
  ) {
    this.displayedColumns = [
      'ID',
      'NAME',
      'EXT',
      'SIZE',
      'VERSION',
      'FRMOD',
      'USMOD',
      'ACTIONS',
    ];
    this.dataSource = new MatTableDataSource();
    this.isLoading = false;
    this.isLoadingForm = false;
    this.btnSmall = false;
    this.ulOptSmall = false;
    this.txtBuscador = '';
  }

  ngOnInit(): void {
    this.onResize();

    /*     this.dataSource.data = [
      {
        ID: '01-ADSI-CA-230120-000001=01',
        NAME: 'Test',
        EXT: '.doc',
        SIZE: '20MB',
        VERSION: '1',
        FRMOD: '22/02/13',
        USMOD: 'CAVA07',
      },
      {
        ID: '01-ADSI-CA-230100-000002=02',
        NAME: 'Test2',
        EXT: '.pdf',
        SIZE: '10MB',
        VERSION: '2',
        FRMOD: '22/02/12',
        USMOD: 'CAVA07',
      },
    ]; */
    this.getDocuments();
  }

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

  registerDocument() {
    this._router.navigate(['sam/GDEL/ADDO/nuevo']);
  }

  public async getShareDocuments() {
    this.dataSource.data = [];
  }

  public async getDocuments() {
    this.isLoading = true;
    let idEnc = localStorage.getItem('idusuario')!;
    let shortEnc = await lastValueFrom(this._encService.shortEncrypt(idEnc));

    let documents: any = await lastValueFrom(
      this._gdelService.getDocumentsByUser(
        shortEnc.response.encrypted,
        1
      )
    );

    if (documents.error) {
      this.openSnackBar(documents.msg);
    } else {
      for (let index = 0; index < documents.response.length; index++) {
        documents.response[index].TAMANIO = this.formatBytes(
          documents.response[index].TAMANIO
        );
      }
      this.dataSource.data = documents.response;
      this.isLoading = false;

    }
    console.log(documents);
  }

  async modifyDocument(idDocument: number) {
    let idDocEnc = await this._encService.encriptar(`${idDocument}`);

    this._router.navigate(['sam/GDEL/ADDO/editar'], {
      queryParams: {
        idDoc: idDocEnc,
      },
    });
  }

  // Método de filtrado de datos
  public applyFilter(event: any, type: string): void {
    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();
    }
  }

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

  selectTab(index: number) {
    this.active = index;
    console.log(index);
    
    switch (index) {
      case 0:
        this.getDocuments();
        break;
      case 1:
        this.getShareDocuments();
        break;
      case 2:
        break;
      default:
        break;
    }
  }

  public openViewer(url: string) {
    let dialogRef: any;
    let fileData = {
      url: url,
    };

    dialogRef = this.dialog.open(WebviewerComponent, {
      data: fileData,
      width: '100%',
    });

    dialogRef.afterClosed().subscribe((result: any) => {
      if (result) {
        console.log(result);
      }
      this.isLoadingForm = false;
    });
  }

  // Método para dar formato a las fechas y horas
  public formatDate(dateRegister: string, dateUpdate: string | null): string {
    let date: string = dateUpdate === null ? dateRegister : dateUpdate;
    let arrDateTime: Array<string> = date.split(' ');
    let arrDate: Array<string> = arrDateTime[0].split('-');
    return `${arrDate[2]}-${arrDate[1]}-${arrDate[0]} ${arrDateTime[1]}`;
  }

  public async alert(type: string, dataElement: any = null) {
    this.isLoadingForm = true;
    let dataDialog: AlertData = {} as AlertData;
    if (type === 'CANCEL') {
      dataDialog = {
        icon: 'warning',
        title: 'Cancelar Solicitud',
        description:
          '¿Está seguro de cancelar la línea de solicitud de compra?',
      };
    }

    // Se ejecuta la alerta
    const dialogRef = this._dialog.open(AlertComponent, {
      data: dataDialog,
      disableClose: true,
      width: '350px',
    });

    // Se obtiene la respuesta obtenida por la alerta
    dialogRef.afterClosed().subscribe((result) => {
      if (result && type === 'CANCEL') {
        console.log(result);
      }
    });
    this.isLoadingForm = false;
  }

  // Funcion para descargar archivos
  async downloadFile(idFile: string) {
    console.log('descargar archivo');

    /*     try{
      let shortAvi = await lastValueFrom(this._encService.shortEncrypt(idFile));
      let idEnc = localStorage.getItem('idusuario');
      let shortEnc = await lastValueFrom(this._encService.shortEncrypt(idEnc!));

      let downloadToken = await lastValueFrom(this._advicesService.getDownloadToken(shortAvi.response.encrypted, shortEnc.response.encrypted, 1));
      //this.downloadLink = "http://git.ittec.mx/sam/public/api/download-file///1";
      this.downloadLink = `http://git.ittec.mx/sam/public/api/download-file/${downloadToken.response.TOKEN}/${shortEnc.response.encrypted}/1`;
      console.log(this.downloadLink);
      this.a?.nativeElement.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);
    } */
  }

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

  formatBytes(bytes: number, decimals = 2) {
    if (bytes === 0) return '0 Bytes';

    const k = 1024;
    const dm = decimals < 0 ? 0 : decimals;
    const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];

    const i = Math.floor(Math.log(bytes) / Math.log(k));

    return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];
  }

  openSnackBar(msg: string) {
    this._snackBar.open(msg, undefined, {
      duration: 2500,
    });
  }
}
