import { LoadingDialogComponent } from './../../../system-admin/catalogues/catalogue-viewer/loading-dialog/loading-dialog.component';
import { MatDialog } from '@angular/material/dialog';
import { CatalogueInformationResponse } from './../../../../interfaces/catalogue.interface';
import { CataloguesService } from './../../../../services/catalogues.service';
import { lastValueFrom } from 'rxjs';
import { EncService } from './../../../../services/enc/enc.service';
import { MatSnackBar } from '@angular/material/snack-bar';
import { ActivatedRoute } from '@angular/router';
import { Component, OnInit, ViewChild } from '@angular/core';
import { Location } from '@angular/common';
import { SpreadsheetComponent } from '@syncfusion/ej2-angular-spreadsheet';

@Component({
  selector: 'app-catalogue-viewer',
  templateUrl: './catalogue-viewer.component.html',
  styleUrls: ['./catalogue-viewer.component.css']
})
export class CatalogueViewerComponent implements OnInit {
  isLoading: boolean;
  hasError: boolean;
  errorStr: string;
  sheets: string[];
  activeSheet?: string;
  displayedColumns: Array<Array<string>>;
  dataSource: Array<Array<any>>;

  @ViewChild('spreadsheet') public spreadsheetObj?: SpreadsheetComponent;

  fileName: string;
  fileOpened: boolean;
  dialogRef: any;

  constructor(
    private _activatedRoute: ActivatedRoute,
    private _location: Location,
    private _snackBar: MatSnackBar,
    private _encService: EncService,
    private _cataloguesService: CataloguesService,
    private _dialog: MatDialog
  ) { 
    this.isLoading = true;
    this.hasError = true;
    this.errorStr = "";
    this.sheets = [];
    this.displayedColumns = [];
    this.dataSource = [];
    this.fileName = "";
    this.fileOpened = false;
  }

  ngOnInit(): void {
    this._activatedRoute.queryParams.subscribe(params => {
      let info = params['info'];
      
      if(info == undefined || info == null || info == ""){
        this.openSnacbar('No se envió ninguna información');
        this._location.back()
      }else{
        this.getData(info);
      }
    });
  }

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

  async getData(id: string){
    try{
      let idUser = localStorage.getItem('idusuario');
      let idUserShort = await lastValueFrom(this._encService.shortEncrypt(idUser!));
      let catInfo: CatalogueInformationResponse = await lastValueFrom(this._cataloguesService.readCatalogue(id, idUserShort.response.encrypted, 1));

      this.fileName = await this._encService.desencriptar(catInfo.response.IDCATALOGO);
      this.hasError = catInfo.error;
      this.errorStr = catInfo.msg;
      this.isLoading = false;

      this.dialogRef = this._dialog.open(LoadingDialogComponent, {
        disableClose: true,
        data: {
          idCatalogo: id
        }
      })

      this.dialogRef.afterClosed().subscribe((res: any) => {
        if(res == 'cerrar'){
          this._location.back();
        }
      });
    }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.openSnacbar(msg);
      this._location.back();
    }
  }

  created(){
    fetch(`http://209.50.56.224/sam/public_files/${this.fileName}`).then(resp => {
      resp.blob().then(fileBlob => {
        let file = new File([fileBlob],this.fileName);
        this.spreadsheetObj?.open({file: file});
      });
    });
  }

  openCompleted(){
    this.fileOpened = true;
    this.dialogRef.close('opened');
  }

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