import { AnnotationWrapper } from '@models/file/annotation.wrapper';
import { effect, Injectable, untracked } from '@angular/core';
import { EntitiesService, ListingService, SearchService } from '@iqser/common-ui';
import { MultiSelectService } from './multi-select.service';
import { PdfViewer } from '../../pdf-viewer/services/pdf-viewer.service';
import { REDAnnotationManager } from '../../pdf-viewer/services/annotation-manager.service';
import { FilterService } from '@iqser/common-ui/lib/filtering';
import { SortingService } from '@iqser/common-ui/lib/sorting';
import { toSignal } from '@angular/core/rxjs-interop';

@Injectable()
export class AnnotationsListingService extends ListingService<AnnotationWrapper> {
    readonly selectedLength = toSignal(this.selectedLength$);

    constructor(
        protected readonly _filterService: FilterService,
        protected readonly _searchService: SearchService<AnnotationWrapper>,
        protected readonly _entitiesService: EntitiesService<AnnotationWrapper, AnnotationWrapper>,
        protected readonly _sortingService: SortingService<AnnotationWrapper>,
        private readonly _multiSelectService: MultiSelectService,
        private readonly _pdf: PdfViewer,
        private readonly _annotationManager: REDAnnotationManager,
    ) {
        super(_filterService, _searchService, _entitiesService, _sortingService);

        effect(
            () => {
                if (this.selectedLength() > 1) {
                    this._multiSelectService.activate();
                }
            },
            { allowSignalWrites: true },
        );
    }

    selectAnnotations(annotations: AnnotationWrapper[] | AnnotationWrapper) {
        annotations = Array.isArray(annotations) ? annotations : [annotations];
        const pageNumber = annotations[annotations.length - 1].pageNumber;

        const multiSelectActive = untracked(this._multiSelectService.active);
        const annotationsToSelect = multiSelectActive ? [...this.selected, ...annotations] : annotations;
        this.#selectAnnotations(annotationsToSelect, pageNumber);
    }

    #selectAnnotations(annotations: AnnotationWrapper[], pageNumber: number) {
        if (!annotations.length) {
            return;
        }

        const multiSelectInactive = untracked(this._multiSelectService.inactive);
        if (multiSelectInactive) {
            this._annotationManager.deselect();
        }

        const currentPage = untracked(this._pdf.currentPage);
        if (pageNumber === currentPage) {
            return this._annotationManager.jumpAndSelect(annotations);
        }

        this._pdf.navigateTo(pageNumber);
        // wait for page to be loaded and to draw annotations
        setTimeout(() => this._annotationManager.jumpAndSelect(annotations), 10);
    }
}
