import { Component, Inject, OnInit } from '@angular/core';
import { MAT_DIALOG_DATA } from '@angular/material/dialog';
import { GdelService } from '../../../../services/gdel.service';
import { lastValueFrom } from 'rxjs';
import { DomSanitizer } from '@angular/platform-browser';

@Component({
    selector: 'app-plane-viewer',
    templateUrl: './plane-viewer.component.html',
    styleUrl: './plane-viewer.component.css',
    standalone: false
})
export class PlaneViewerComponent implements OnInit {
  isLoading: boolean;
  hasError: boolean;
  errorStr: string;
  fileURL: string;

  constructor(
    @Inject(MAT_DIALOG_DATA) private _data: any,
    private _gdelService: GdelService,
    public sanitizer: DomSanitizer,
  ) {
    this.isLoading = true;
    this.hasError = false;
    this.errorStr = '';
    this.fileURL = '';
  }

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

  private async getPublicURI(){
    try{
      let idUser = localStorage.getItem('idusuario')!;
      let fileURI = await lastValueFrom(this._gdelService.getPublicDocumentUrl(
        this._data.idFile,
        idUser,
        1
      ));

      this.hasError = fileURI.error;
      this.errorStr = fileURI.msg;

      if(!this.hasError){
        this.fileURL = fileURI.response.public_uri;
      }

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

      this.hasError = true;
      this.isLoading = false;
    }
  }
}
