import { inject, Injectable } from '@angular/core';
import { GenericService, Toaster } from '@iqser/common-ui';
import { Earmark, EarmarkOperation, EarmarkResponse } from '@red/domain';
import { catchError, map, tap } from 'rxjs/operators';
import { firstValueFrom, of } from 'rxjs';
import { AnnotationWrapper } from '@models/file/annotation.wrapper';
import { marker as _ } from '@biesbjerg/ngx-translate-extract-marker';

@Injectable({
    providedIn: 'root',
})
export class EarmarksService extends GenericService<EarmarkResponse> {
    protected readonly _defaultModelPath = '';
    readonly #toaster = inject(Toaster);

    getEarmarks(dossierId: string, fileId: string) {
        const request = this._http.get<{ highlights: Earmark[] }>(`/${this._serviceName}/${this.#getPath(dossierId, fileId)}`).pipe(
            map(response => response.highlights),
            map(highlights => highlights.map(highlight => AnnotationWrapper.fromEarmark(highlight))),
            map(highlights => highlights.sort((h1, h2) => h1.color.localeCompare(h2.color))),
            catchError(() => of([] as AnnotationWrapper[])),
        );

        return firstValueFrom(request);
    }

    performHighlightsAction(ids: string[], dossierId: string, fileId: string, operation: EarmarkOperation) {
        return this._post({ ids }, `/${this._serviceName}/${this.#getPath(dossierId, fileId)}/${operation}`).pipe(
            tap(() => this.#toaster.success(_('highlight-action-dialog.success'), { params: { operation } })),
        );
    }

    #getPath(dossierId: string, fileId: string): string {
        return `dossiers/${dossierId}/files/${fileId}/highlights`;
    }
}
