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

@Injectable()
export class ReadableRedactionsService {
    private readonly _convertPath = inject(BASE_HREF_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);
    readonly active$: Observable<boolean>;

    constructor(
        private readonly _pdf: PdfViewer,
        private readonly _translateService: TranslateService,
        private readonly _annotationManager: REDAnnotationManager,
        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 => {
            const isSuggestion = annotation.getCustomData('suggestion');
            annotation['Opacity'] = restoreToOriginal || isSuggestion ? parseFloat(annotation.getCustomData('opacity')) : 0.5;
        });
    }

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