import { inject, Injectable } from '@angular/core';
import { UserPreferenceService } from '@users/user-preference.service';
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 { BASE_HREF_FN } from '@iqser/common-ui/lib/utils';

@Injectable()
export class LayersService {
    private readonly _convertPath = inject(BASE_HREF_FN);
    readonly #enableIcon = this._convertPath('/assets/icons/general/pdftron-action-disable-layers.svg');
    readonly #disableIcon = this._convertPath('/assets/icons/general/pdftron-action-enable-layers.svg');

    private _active = false;

    constructor(
        private readonly _pdf: PdfViewer,
        private readonly _documentViewer: REDDocumentViewer,
        private readonly _userPreferenceService: UserPreferenceService,
        private readonly _translateService: TranslateService,
    ) {}

    get toggleLayersBtnTitle(): string {
        return this._translateService.instant(_('pdf-viewer.toggle-layers'), {
            active: this._active,
        });
    }

    get toggleLayersBtnIcon(): string {
        const tooltipsDisabled = this._active;
        return tooltipsDisabled ? this.#enableIcon : this.#disableIcon;
    }

    resetLayers() {
        this._active = false;
        this.#updateButton();
    }

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

        this._active = !this._active;
        this.#updateButton();
    }

    #updateButton() {
        this._pdf.instance.UI.updateElement(HeaderElements.TOGGLE_LAYERS, {
            title: this.toggleLayersBtnTitle,
            img: this.toggleLayersBtnIcon,
        });
    }
}
