import { Component, ChangeDetectionStrategy, ChangeDetectorRef } from '@angular/core';
import { DomainPrinterService } from '@domain/printer';
import { DomainTaskCalendarService } from '@domain/task-calendar';
import { PrintModalComponent, PrintModalData } from '@modal/printer';
import { FileDTO } from '@swagger/eis';
import { UiModalRef, UiModalService } from '@ui/modal';
import { PDFDocumentProxy } from 'ng2-pdf-viewer';
import { PdfViewerModalData } from './pdf-viewer-modal.data';

@Component({
  selector: 'page-pdf-viewer-modal',
  templateUrl: 'pdf-viewer-modal.component.html',
  styleUrls: ['pdf-viewer-modal.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class PdfViewerModalComponent {
  objectURL: string;

  file: FileDTO;

  page = 1;

  totalPages = 1;

  constructor(
    private modalRef: UiModalRef<any, PdfViewerModalData>,
    private cdr: ChangeDetectorRef,
    private uiModal: UiModalService,
    private taskCalendarService: DomainTaskCalendarService,
    private domainPrinterService: DomainPrinterService
  ) {
    this.objectURL = URL.createObjectURL(this.modalRef.data.content);
    this.file = this.modalRef.data.file;
  }

  close() {
    this.modalRef.close();
  }

  callBackFn(pdf: PDFDocumentProxy) {
    this.totalPages = pdf.numPages;
    this.cdr.markForCheck();
  }

  print() {
    const blob = this.modalRef.data.content;
    const reader = new FileReader();
    reader.readAsDataURL(blob);
    reader.onloadend = () => {
      const base64data = reader.result as string;
      const data: PrintModalData = {
        printerType: 'Office',
        print: (printer) =>
          this.domainPrinterService.printPdf({ printer, data: this.taskCalendarService.removeMetaDataFromBase64(base64data) }).toPromise(),
      };
      this.uiModal.open({
        content: PrintModalComponent,
        data,
        config: {
          panelClass: [],
          showScrollbarY: false,
        },
      });
    };
  }
}
