import { Injectable } from '@angular/core';
import { CanActivate, Router } from '@angular/router';
import { REDDocumentViewer } from './document-viewer.service';
import { PdfViewer } from './pdf-viewer.service';
import { REDAnnotationManager } from './annotation-manager.service';
import { ViewerHeaderService } from './viewer-header.service';
import { LoadingService } from '@iqser/common-ui';
import { WebViewerInstance } from '@pdftron/webviewer';

@Injectable()
export class WebViewerLoadedGuard implements CanActivate {
    constructor(
        private readonly _documentViewer: REDDocumentViewer,
        private readonly _pdf: PdfViewer,
        private readonly _router: Router,
        private readonly _annotationManager: REDAnnotationManager,
        private readonly _viewerHeaderService: ViewerHeaderService,
        private readonly _loadingService: LoadingService,
    ) {}

    async canActivate(_, state) {
        if (this._pdf.instance) {
            return true;
        }

        this._loadingService.start();

        let instance: WebViewerInstance | undefined;
        try {
            instance = await this._pdf.init(document.getElementById('viewer'));
        } catch {
            return this._router.navigateByUrl(state.url);
        }

        this._annotationManager.init(instance.Core.annotationManager);
        this._documentViewer.init(instance.Core.documentViewer);
        this._viewerHeaderService.init();

        return !!this._pdf.instance;
    }
}
