import { customElement } from "lit/decorators.js";
import { translate } from "../../locales";
import { PrimariaBroker } from "../broker/primaria-broker";
import { PrimariaNotificationService } from "../notification-service/notification-service";
import { pdfViwerEvents } from "./events";
import { PdfSelector } from "./pdf-visor/pdf-selector/pdf-selector";
import { PdfVisor } from "./pdf-visor/pdf-visor";
import { pdfViewerId } from "./constants";

export interface PdfData {
  id: string;
  name: string;
  date: string;
  url?: string;
  b64?: string;
}

export interface IPdfDocument {
  id: string;
  pdfName: string;
  data: PdfData;
}

export interface PdfViewerOptions {
  autoNavigate?: boolean;
}

export class PdfViewerManager {
  constructor(
    private broker: PrimariaBroker,
    private notificationService: PrimariaNotificationService,
  ) {
    if (!customElements.get("pdf-visor")) {
      customElement("pdf-visor")(PdfVisor);
    }
    if (!customElements.get("pdf-selector")) {
      customElement("pdf-selector")(PdfSelector);
    }
  }

  private pdfs: IPdfDocument[] = [];
  private activePdf: IPdfDocument | null = null;

  add(data: PdfData, options?: PdfViewerOptions) {
    const pdf: IPdfDocument = {
      id: data.id,
      pdfName: data.name,
      data
    };

    if (!data.url && !data.b64) {
      this.notificationService.error(translate("pdfManager.missingData"));
      return;
    }
    if (data.url && data.b64) {
      this.notificationService.error(translate("pdfManager.duplicatedSource"));
      return;
    }
    if (this.pdfs.some((p) => p.id === pdf.id)) {
      this.notificationService.warning(translate("pdfManager.alreadyUploaded"));
    } else {
      this.pdfs.push(pdf as IPdfDocument);
      this.broker.publish(pdfViwerEvents.added, pdf);

      if (options?.autoNavigate) {
        // Navigate automatically to PDF viewer
        setTimeout(() => {
          import("../api").then(({ shellApi }) => {
            shellApi.regionManager.activateMainView(pdfViewerId);
          });
        }, 150);
      } else {
        this.notificationService.success(translate("pdfManager.tooltipMessage"));
      }
    }

    return pdf;
  }

  delete(pdfId: string) {
    this.pdfs = this.pdfs.filter((pdf) => pdf.id !== pdfId);

    if (this.activePdf?.id === pdfId) {
      this.activePdf = null;
    }

    this.broker.publish(pdfViwerEvents.deleted, { id: pdfId });
  }

  getPdfs(): IPdfDocument[] {
    return this.pdfs;
  }
}

export const createPdfViewerManager = (broker: PrimariaBroker, notificationService: PrimariaNotificationService) =>
  new PdfViewerManager(broker, notificationService);
