import { effect, Injectable, Signal, signal } from '@angular/core';
import { bool } from '@iqser/common-ui/lib/utils';
import { getLocalStorageDataByFileId, setLocalStorageDataByFileId } from '@utils/local-storage';
import { REDAnnotationManager } from '../../pdf-viewer/services/annotation-manager.service';
import { HIDE_SKIPPED } from '../utils/constants';
import { FilePreviewStateService } from './file-preview-state.service';

@Injectable()
export class SkippedService {
    readonly #hideSkipped = signal(false);
    readonly hideSkipped: Signal<boolean>;

    constructor(
        private readonly _annotationManager: REDAnnotationManager,
        private readonly _state: FilePreviewStateService,
    ) {
        this.hideSkipped = this.#hideSkipped.asReadonly();

        effect(() => {
            const ignored = this._annotationManager.get(a => bool(a.getCustomData('skipped')));
            if (this.#hideSkipped()) {
                this._annotationManager.hide(ignored);
            } else {
                this._annotationManager.show(ignored);
            }

            setLocalStorageDataByFileId(this._state.fileId, HIDE_SKIPPED, this.#hideSkipped());
        });

        if (getLocalStorageDataByFileId(this._state.fileId, HIDE_SKIPPED)) {
            this.toggleSkipped();
        }
    }

    toggleSkipped(): void {
        this.#hideSkipped.set(!this.#hideSkipped());
    }
}
