import { computed, effect, inject, Injectable, signal } from '@angular/core';
import { HeaderElements } from '../../file-preview/utils/constants';
import { marker as _ } from '@biesbjerg/ngx-translate-extract-marker';
import { TranslateService } from '@ngx-translate/core';
import { PdfViewer } from './pdf-viewer.service';
import { REDDocumentViewer } from './document-viewer.service';
import { UI_ROOT_PATH_FN } from '@common-ui/utils';

@Injectable()
export class LayersService {
    readonly #convertPath = inject(UI_ROOT_PATH_FN);
    readonly #icon = this.#convertPath('/assets/icons/general/pdftron-action-layers.svg');

    readonly active = signal(false);
    constructor(
        private readonly _pdf: PdfViewer,
        private readonly _documentViewer: REDDocumentViewer,
        private readonly _translateService: TranslateService,
    ) {}

    get toggleLayersBtnIcon(): string {
        return this.#icon;
    }

    resetLayers() {
        this.active.set(false);
    }

    async toggleLayers(): Promise<void> {
        const layers = await this._documentViewer.document.getLayersArray();
        layers.forEach(layer => {
            if ('Layout grid' === layer.name) {
                layer.visible = !this.active();
            }
        });

        this._documentViewer.document.setLayersArray(layers);
        this._documentViewer.refreshAndUpdateView();
    }

    updateState() {
        this.#updateIconState();
        this.#updateButton();
    }

    #updateIconState() {
        const element = this._pdf.instance.UI.iframeWindow.document.querySelector(`[data-element=${HeaderElements.TOGGLE_LAYERS}]`);
        if (!element) return;
        if (this.active()) {
            element.classList.add('active');
        } else {
            element.classList.remove('active');
        }
    }

    #updateButton() {
        this._pdf.instance?.UI.updateElement(HeaderElements.TOGGLE_LAYERS, {
            title: this._translateService.instant(_('pdf-viewer.header.toggle-layers'), {
                active: this.active(),
            }),
        });
    }
}
