import { DOCUMENT } from '@angular/common';
import { Component, Inject, OnInit } from '@angular/core';
import { FormControl, FormGroup } from '@angular/forms';
import { MatDialogRef } from '@angular/material/dialog';
import { MatSnackBar } from '@angular/material/snack-bar';
import { MatTableDataSource } from '@angular/material/table';
import { lastValueFrom } from 'rxjs';
import { FindedFile, FindedFilesResponse } from 'src/app/interfaces/finded-files.interface';
import { AdvicesService } from 'src/app/services/advices.service';
import { EncService } from 'src/app/services/enc/enc.service';
//import { GdelService } from 'src/app/services/gdel/gdel.service';

@Component({
  selector: 'app-search-file-dialog',
  templateUrl: './search-file-dialog.component.html',
  styleUrls: ['./search-file-dialog.component.css']
})
export class SearchFileDialogComponent implements OnInit {
  isSearching: boolean;
  searchExecuted: boolean;
  dataSource?: MatTableDataSource<FindedFile>;
  displayedColumns = ['CODIGO', 'VERSION', 'NOMBRE', 'TAMANIO', 'ACCIONES'];

  searchFilters?: FormGroup;
  startDate: Date | null;
  endDate: Date | null;

  attachedFiles: FindedFile[];

  constructor(
    private _snackBar: MatSnackBar,
    private _encService: EncService,
    //private _gdelService: GdelService,
    private _dialogReference: MatDialogRef<SearchFileDialogComponent>,
    private _advicesServices: AdvicesService,
    @Inject(DOCUMENT) private _document: Document,
  ) { 
    this.isSearching = false;
    this.searchExecuted = false;
    this.startDate = null;
    this.endDate = null;

    this.searchFilters = new FormGroup({
      moduleControl: new FormControl(''),
      clasificationControl: new FormControl(''),
      startDateControl: new FormControl(this.startDate),
      endDateControl: new FormControl(this.endDate),
      documentNameControl: new FormControl(''),
    });

    this.dataSource = new MatTableDataSource();
    this.attachedFiles = [];
  }

  ngOnInit(): void {
  }

  async searchFiles(){
    try{
      this.isSearching = true;
      this.searchExecuted = true;

      let form = this.searchFilters?.getRawValue();
      let hasOneValue = false;

      if(form.moduleControl != ""){
        hasOneValue = true;
      }else if(form.clasificationControl != ""){
        hasOneValue = true;
      }else if(form.startDateControl != null){
        hasOneValue = true;
      }else if(form.endDateControl != null){
        hasOneValue = true;
      }else if(form.documentNameControl != ""){
        hasOneValue = true;
      }

      if(!hasOneValue){
        this.openSnackBar('Para realizar la búsqueda utilice al menos un filtro.');
      }else{
        let idUser = localStorage.getItem('idusuario');
        let shortEnc = await lastValueFrom(this._encService.shortEncrypt(idUser!));

        let mod = form.moduleControl == "" ? '-' : form.moduleControl;
        let cla = form.clasificationControl == "" ? '-' : form.clasificationControl;
        let dna = form.documentNameControl == "" ? '-' : form.documentNameControl;

        let sda = '-';
        let eda = '-';

        if(form.startDateControl != null){
          let startDate = form.startDateControl as Date;
          let startYear = startDate.getFullYear().toString().substring(2, 4);
          let startMonth = startDate.getMonth() + 1 < 10 ? `0${startDate.getMonth() + 1}` : `${startDate.getMonth() + 1}`;
          let startDay = startDate.getDate() < 10 ? `0${startDate.getDate()}` : `${startDate.getDate()}`;
          
          sda = `${startYear}${startMonth}${startDay}`;
        }

        if(form.endDateControl != null){
          let endDate = form.endDateControl as Date;
          let endYear = endDate.getFullYear().toString().substring(2, 4);
          let endMonth = endDate.getMonth() + 1 < 10 ? `0${endDate.getMonth() + 1}` : `${endDate.getMonth() + 1}`;
          let endDay = endDate.getDate() < 10 ? `0${endDate.getDate()}` : `${endDate.getDate()}`;
          
          eda = `${endYear}${endMonth}${endDay}`;
        }

        //let files: FindedFilesResponse = await lastValueFrom(this._gdelService.getFiles(mod, cla, sda, eda, dna, shortEnc.response.encrypted, 1));
        
        /*if(files.error){
          this.openSnackBar(files.msg);
        }else{
          this.dataSource = new MatTableDataSource(files.response);
        }*/

        this.isSearching = false;
      }
    }catch(error: any){
      if(error.error == undefined){
        this.openSnackBar('Ocurrió un error inesperado.');
      }else if(error.error.msg == undefined){
        this.openSnackBar('Ocurrió un error inesperado.');
      }else{
        this.openSnackBar(error.error.msg);
      }
      this.isSearching = false;
    }
  }

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

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

  clearFilters(){
    this.searchExecuted = false;
    this.dataSource = new MatTableDataSource();

    this.searchFilters?.controls['moduleControl'].setValue('');
    this.searchFilters?.controls['clasificationControl'].setValue('');
    this.searchFilters?.controls['startDateControl'].setValue(null);
    this.searchFilters?.controls['endDateControl'].setValue(null);
    this.searchFilters?.controls['documentNameControl'].setValue('');
  }

  attachFile(file: FindedFile){
    let search = this.attachedFiles.filter(item => item.CODIGO == file.CODIGO && item.VERSION == file.VERSION);
    if(search.length > 0){
      let attachedAux: FindedFile[] = [];
      this.attachedFiles.forEach(item => {
        if(item.CODIGO != file.CODIGO && item.VERSION != file.VERSION){
          attachedAux.push(item);
        }
      });

      this.attachedFiles = attachedAux;
    }else{
      this.attachedFiles.push(file);
    }
  }

  isAttached(file: FindedFile){
    let search = this.attachedFiles.filter(item => item.CODIGO == file.CODIGO && item.VERSION == file.VERSION);
    return search.length > 0;
  }

  async downloadFile(file: FindedFile){
    try{
      let idUser = localStorage.getItem('idusuario');
      let shortEnc = await lastValueFrom(this._encService.shortEncrypt(idUser!));

      let fileName = `${file.CODIGO}=${file.VERSION}=${file.NOMBRE}`;
      let fileEnc = await this._encService.encriptar(fileName);
      let fileShort = await lastValueFrom(this._encService.shortEncrypt(fileEnc));

      let downloadToken = await lastValueFrom(this._advicesServices.getDownloadToken(
        fileShort.response.encrypted,
        shortEnc.response.encrypted,
        1
      ));

      let download = this._document.getElementById(`download-${file.CODIGO}`) as HTMLAnchorElement;
      download.href = `http://git.ittec.mx/sam/public/api/download-file/${downloadToken.response.TOKEN}/${shortEnc.response.encrypted}/1`;
      download.download = fileName;
      download.click();
    }catch(error: any){
      if(error.error == undefined){
        this.openSnackBar('Ocurrió un error inesperado');
      }else if(error.error.msg == undefined){
        this.openSnackBar('Ocurrió un error inesperado');
      }else{
        this.openSnackBar(error.error.msg);
      }
    }
  }

  async openViewer(file: FindedFile){
    this.openSnackBar('En desarrollo');
  }

  saveFiles(){
    let attachedStr = JSON.stringify(this.attachedFiles);
    this._dialogReference.close(attachedStr);
  }
}
