import { AfterViewInit, Component, ElementRef, Input, OnChanges, SimpleChanges, ViewChild } from '@angular/core'; import { SpinnerService } from '@core/services/spinner.service'; import { ApplicationAttachmentService } from '@features/application-view/application-attachments/application-attachments.service'; import { LogService } from '@yourcause/common/logging'; import { DocumentTemplateService } from '../document-template.service'; import { DocumentTemplateDetailForUI } from '../document-template.typing'; @Component({ selector: 'gc-merge-document-preview', templateUrl: './merge-document-preview.component.html', styleUrls: ['./merge-document-preview.component.scss'] }) export class MergeDocumentPreviewComponent implements OnChanges, AfterViewInit { @Input() templateId: number; @Input() applicationIds: number[]; @ViewChild('previewContainer') previewContainer: ElementRef; selectedTemplate: DocumentTemplateDetailForUI; previewHtml = ''; loading = false; previewError = false; constructor ( private documentTemplateService: DocumentTemplateService, private spinnerService: SpinnerService, private applicationAttachmentService: ApplicationAttachmentService, private logger: LogService ) { } ngOnChanges (changes: SimpleChanges) { if (changes.templateId) { this.setSelectedTemplate(); } } ngAfterViewInit () { this.setPreviewHtml(); } private setPreviewHtml () { if ( this.previewContainer?.nativeElement && !this.previewError ) { const iframe: HTMLIFrameElement = this.previewContainer.nativeElement; iframe.contentDocument.body.innerHTML = this.previewHtml; } } async setSelectedTemplate () { this.selectedTemplate = null; if (this.templateId) { this.spinnerService.startSpinner(); this.loading = true; await this.documentTemplateService.setDocumentTemplateDetail(this.templateId); this.selectedTemplate = this.documentTemplateService.detailMap[this.templateId]; if (this.applicationIds?.length === 1) { try { this.previewHtml = await this.applicationAttachmentService.getMergePreview( this.templateId, this.applicationIds[0] ); this.previewError = false; if (this.previewHtml === null) { this.previewError = true; } } catch (e) { this.logger.error(e); this.previewError = true; } } else { this.previewHtml = this.selectedTemplate.templateHtml; } if (this.previewHtml) { this.previewHtml = this.documentTemplateService.attachStyleTag(this.previewHtml, this.selectedTemplate.margins); } this.loading = false; this.spinnerService.stopSpinner(); } else { this.previewHtml = ''; this.previewError = false; } this.setPreviewHtml(); } }