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

@Component({
    selector: 'app-catalogue-viewer',
    templateUrl: './catalogue-viewer.component.html',
    styleUrl: './catalogue-viewer.component.css',
    standalone: false
})
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(
    @Inject(DOCUMENT) private _document: Document,
    private _activatedRoute: ActivatedRoute,
    private _location: Location,
    private _encService: EncService,
    private _cataloguesService: CataloguesService,
    private _dialog: MatDialog,
    private _resourcesService: ResourcesService,
  ) { 
    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._resourcesService.openSnackBar('No se envió ninguna información');
        this._location.back()
      }else{
        this.getData(info);
      }
    });
  }

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

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

      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._resourcesService.openSnackBar(msg);
      this._location.back();
    }
  }

  disableLicensing(){
    setTimeout(() => {
      let body = this._document.body;
      for(let i = 0; i < body.children.length; i++){
        let bodyChild = body.children[i];
        if(bodyChild.tagName == 'DIV'){
          if(bodyChild.classList.length == 0){
            bodyChild.classList.add('hidden');
          }
        }
      }
    }, 100);
  }

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

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