import { Injectable } from '@angular/core';
import { GenericService, QueryParam } from '@iqser/common-ui';
import { IRedactionLog, ISectionGrid } from '@red/domain';
import { catchError } from 'rxjs/operators';
import { firstValueFrom, of } from 'rxjs';

@Injectable({
    providedIn: 'root',
})
export class RedactionLogService extends GenericService<unknown> {
    protected readonly _defaultModelPath = '';

    async getRedactionLog(dossierId: string, fileId: string, withManualRedactions?: boolean) {
        const queryParams: QueryParam[] = [];
        if (withManualRedactions) {
            queryParams.push({ key: 'withManualRedactions', value: withManualRedactions });
        }

        const redactionLog$ = this._getOne<IRedactionLog>([dossierId, fileId], 'redactionLog', queryParams);
        const redactionLog = await firstValueFrom(redactionLog$.pipe(catchError(() => of({} as IRedactionLog))));
        redactionLog.redactionLogEntry.sort((a, b) => a.positions[0].page - b.positions[0].page);
        return redactionLog;
    }

    getSectionGrid(dossierId: string, fileId: string) {
        return this._getOne<ISectionGrid>([dossierId, fileId], 'sectionGrid');
    }
}
