import { inject } from '@angular/core';
import { CanActivateFn, ResolveFn, 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';
import { NGXLogger } from 'ngx-logger';
import { DOCUMENT } from '@angular/common';

export function webViewerLoadedGuard(): CanActivateFn | ResolveFn<boolean> {
    return async (_, state) => {
        const pdf = inject(PdfViewer);
        const logger = inject(NGXLogger);

        if (pdf.instance) {
            logger.info('[PDF] WebViewerGuard already loaded.');
            return true;
        }

        inject(LoadingService).start();
        const router = inject(Router);
        const annotationManager = inject(REDAnnotationManager);
        const documentViewer = inject(REDDocumentViewer);
        const viewerHeaderService = inject(ViewerHeaderService);

        let instance: WebViewerInstance | undefined;
        try {
            instance = await pdf.init(inject(DOCUMENT).getElementById('viewer'));
        } catch (e) {
            const redirectUrl = state.url.split('/').slice(0, -2).join('/');
            logger.warn('[PDF] WebViewerGuard error: ', e, 'redirecting to', redirectUrl);
            return router.navigateByUrl(redirectUrl); // redirect to dossier page
        }

        annotationManager.init(instance.Core.annotationManager);
        documentViewer.init(instance.Core.documentViewer);
        viewerHeaderService.init();

        return !!pdf.instance;
    };
}
