import { HttpClient } from '@angular/common/http';
import { ComponentFactoryResolver, Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { StorageService } from 'src/app/core/services/storage.service';
import { ToastService } from 'src/app/services/toast.service';
import { environment } from '../../environments/environment';
@Injectable({
  providedIn: 'root',
})
export class DocumentService {
  constructor(
    private http: HttpClient,
    public storage: StorageService,
    private toast: ToastService
  ) {}

  public listTemplate(activeModuleName: any): Observable<[]> {
    return this.http
      .post<any>(`${environment.API_URL}v1/generateDoc/templates`, {
        activeModuleName: activeModuleName,
      })
      .pipe(
        map((reportingListTemplate) => {
          return reportingListTemplate;
        })
      );
  }

  public genetateDocuments(payload: any, filename: string): any {
    return this.http
      .post<any>(
        `${environment.API_URL}v1/generateDoc/file`,
        {
          templateId: payload.templateId,
          templateName: payload.templateName,
          activeModuleId: payload.activeModuleId,
          activeModuleName: payload.activeModuleName,
        },
        { observe: 'body', responseType: 'blob' as 'json'}
      )
      .pipe(
        map(
          (resultsDoc: any) => {
            let binaryData = [];
            binaryData.push(resultsDoc);
            var file = new File([resultsDoc], `${filename}`);
            if(resultsDoc.type === 'application/json') {
              const promise = file.text();
              promise.then( (data) => {
                if(JSON.parse(data).success === false) {
                  this.toast.showError(JSON.parse(data).message)
                }
              })
            }
            else {
              let downloadLink = document.createElement('a');
              downloadLink.href = window.URL.createObjectURL(file); 
              downloadLink.setAttribute('download', `${filename}`);
              document.body.appendChild(downloadLink);
              downloadLink.click();
            }
            return true;
          },
          (err: any) => {
            this.toast.showError(err.message);
          }
        )
      );
  }

  /**
   * Download a document file by its UUID from ESTAIR backend
   */
  public downloadByUuid(uuid: string, filename: string): void {
    this.http
      .get(`${environment.DATA_URL}admin/documents/${uuid}/download`, {
        responseType: 'blob',
        observe: 'response',
      })
      .subscribe({
        next: (response: any) => {
          const blob = new Blob([response.body]);
          const downloadLink = document.createElement('a');
          const url = window.URL.createObjectURL(blob);
          downloadLink.href = url;
          downloadLink.setAttribute('download', filename);
          document.body.appendChild(downloadLink);
          downloadLink.click();
          downloadLink.remove();
          window.URL.revokeObjectURL(url);
        },
        error: (err: any) => {
          if (err.status === 404) {
            this.toast.showError('Fichier introuvable sur le serveur');
          } else {
            this.toast.showError('Erreur lors du téléchargement du fichier');
          }
        },
      });
  }

  public getNameDocuments(payload: any): any {
    return this.http
      .post<any>(`${environment.API_URL}v1/generateDoc/fileName`, {
        templateId: payload.templateId,
        templateName: payload.templateName,
        activeModuleId: payload.activeModuleId,
        activeModuleName: payload.activeModuleName,
      })
      .pipe(
        map((result: any) => {
          return result;
        })
      );
  }
}
