import { AnnotationWrapper } from '@models/file/annotation.wrapper';
import { Injectable, OnDestroy } from '@angular/core';
import { EntitiesService, ListingService, SearchService } from '@iqser/common-ui';
import { filter, tap } from 'rxjs/operators';
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 { Subscription } from 'rxjs';
import { FilterService } from '@iqser/common-ui/lib/filtering';
import { SortingService } from '@iqser/common-ui/lib/sorting';

@Injectable()
export class AnnotationsListingService extends ListingService<AnnotationWrapper> implements OnDestroy {
    readonly #subscriptions: Subscription;

    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);

        this.#subscriptions = this.selectedLength$
            .pipe(
                filter(length => length > 1),
                tap(() => this._multiSelectService.activate()),
            )
            .subscribe();
    }

    ngOnDestroy() {
        this.#subscriptions.unsubscribe();
    }

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

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

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

        if (this._multiSelectService.inactive()) {
            this._annotationManager.deselect();
        }

        if (pageNumber === this._pdf.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), 300);
    }
}
