import { Injectable } from '@angular/core';
import * as pdfjs from 'pdfjs-dist';

@Injectable({
  providedIn: 'root'
})
export class PdfService {

  constructor() { 
    pdfjs.GlobalWorkerOptions.workerSrc = 'js/pdf.worker.js';
  }

  async convertToImage(pdfFile: File): Promise<string[]> {
    const pdfData = await this.readFileAsArrayBuffer(pdfFile);
    const pdf = await pdfjs.getDocument({ data: pdfData }).promise;
    const numPages = pdf.numPages;
    const images = [];
    for (let i = 1; i <= numPages; i++) {
      const page = await pdf.getPage(i);
      const viewport = page.getViewport({ scale: 1.0 });
      const canvas = document.createElement('canvas');
      const context = canvas.getContext('2d');

      canvas.height = viewport.height;
      canvas.width = viewport.width;

      const renderContext : any = {
        canvasContext: context,
        viewport: viewport
      };
      await page.render(renderContext).promise;
      const imageData = canvas.toDataURL('image/png');
      images.push(imageData);
    }
    return images;
  }

  async convertToImageString(pdfFile: string): Promise<string[]> {
    const pdf = await pdfjs.getDocument(pdfFile).promise;
    const numPages = pdf.numPages;
    const images = [];
    for (let i = 1; i <= numPages; i++) {
      const page = await pdf.getPage(i);
      const viewport = page.getViewport({ scale: 1.0 });
      const canvas = document.createElement('canvas');
      const context = canvas.getContext('2d');

      canvas.height = viewport.height;
      canvas.width = viewport.width;

      const renderContext : any = {
        canvasContext: context,
        viewport: viewport
      };
      await page.render(renderContext).promise;
      const imageData = canvas.toDataURL('image/png');
      images.push(imageData);
    }
    return images;
  }

  private readFileAsArrayBuffer(file: File): Promise<ArrayBuffer> {
    return new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.onload = () => {
        if (reader.result instanceof ArrayBuffer) {
          resolve(reader.result);
        } else {
          reject(new Error('Erreur de lecture du fichier PDF'));
        }
      };
      reader.onerror = () => {
        reject(new Error('Erreur de lecture du fichier PDF'));
      };
      reader.readAsArrayBuffer(file);
    });
  }


  
}
