import { inject, Injectable } from '@angular/core';
import { marker as _ } from '@biesbjerg/ngx-translate-extract-marker';
import { TranslateService } from '@ngx-translate/core';
import { Core } from '@pdftron/webviewer';
import { BehaviorSubject, Observable } from 'rxjs';
import { HeaderElements } from '../../file-preview/utils/constants';
import { AnnotationDrawService } from './annotation-draw.service';
import { PdfViewer } from './pdf-viewer.service';
import { UI_ROOT_PATH_FN } from '@common-ui/utils';
import Annotation = Core.Annotations.Annotation;

@Injectable()
export class ReadableRedactionsService {
    readonly active$: Observable<boolean>;
    readonly #convertPath = inject(UI_ROOT_PATH_FN);
    readonly #enableIcon = this.#convertPath('/assets/icons/general/redaction-preview.svg');
    readonly #disableIcon = this.#convertPath('/assets/icons/general/redaction-final.svg');
    readonly #active$ = new BehaviorSubject<boolean>(true);

    constructor(
        private readonly _pdf: PdfViewer,
        private readonly _translateService: TranslateService,
        private readonly _annotationDrawService: AnnotationDrawService,
    ) {
        this.active$ = this.#active$.asObservable();
    }

    get active() {
        return this.#active$.getValue();
    }

    get toggleReadableRedactionsBtnTitle(): string {
        return this._translateService.instant(_('pdf-viewer.toggle-readable-redactions'), {
            active: this.active,
        });
    }

    get toggleReadableRedactionsBtnIcon(): string {
        return this.active ? this.#enableIcon : this.#disableIcon;
    }

    toggleReadableRedactions(): void {
        this.#active$.next(!this.active);

        this._pdf.instance.UI.updateElement(HeaderElements.TOGGLE_READABLE_REDACTIONS, {
            title: this.toggleReadableRedactionsBtnTitle,
            img: this.toggleReadableRedactionsBtnIcon,
        });

        if (!this.active) {
            this.setCustomDrawHandler();
        } else {
            this.restoreDraw();
        }
    }

    setCustomDrawHandler(): void {
        const annotationClass: any = this._pdf.instance.Core.Annotations.TextHighlightAnnotation;
        this._pdf.instance.Core.Annotations.setCustomDrawHandler(
            annotationClass,
            (ctx: CanvasRenderingContext2D, pageMatrix, rotation, options) => {
                const annotation = options.annotation;
                ctx.globalCompositeOperation = 'source-over';
                ctx.fillStyle = annotation.getCustomData('appliedRedactionColor');
                ctx.fillRect(annotation.getX(), annotation.getY(), annotation.getWidth(), annotation.getHeight());
            },
            {
                generateAppearance: false,
            },
        );
    }

    restoreDraw(): void {
        const annotationClass: any = this._pdf.instance.Core.Annotations.TextHighlightAnnotation;
        this._pdf.instance.Core.Annotations.restoreDraw(annotationClass);
    }

    setAnnotationsOpacity(annotations: Annotation[], restoreToOriginal = false) {
        annotations.forEach(annotation => {
            annotation['Opacity'] = restoreToOriginal ? parseFloat(annotation.getCustomData('opacity')) : 1;
        });
    }

    setAnnotationsColor(annotations: Annotation[], customData: string) {
        annotations.forEach(annotation => {
            const color = this._annotationDrawService.convertColor(annotation.getCustomData(customData));
            annotation['StrokeColor'] = color;
            annotation['FillColor'] = color;
        });
    }
}
