import { inject, Injectable } from '@angular/core';
import { GenericService, isIqserDevMode, Toaster } from '@iqser/common-ui';
import { EntryStates, IEntityLog, IEntityLogEntry, ISectionGrid } from '@red/domain';
import { firstValueFrom, of } from 'rxjs';
import { catchError } from 'rxjs/operators';

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

    async getEntityLog(dossierId: string, fileId: string) {
        const queryParams = [{ key: 'includeUnprocessed', value: true }];
        const entityLog$ = this._getOne<IEntityLog>([dossierId, fileId], 'entityLog', queryParams);
        const entityLog = await firstValueFrom(entityLog$.pipe(catchError(() => of({} as IEntityLog))));
        entityLog.entityLogEntry = this.#filterInvalidEntries(entityLog.entityLogEntry);
        entityLog.entityLogEntry.sort((a, b) => a.positions[0].pageNumber - b.positions[0].pageNumber);
        return entityLog;
    }

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

    #filterInvalidEntries(entityLogEntry: IEntityLogEntry[]) {
        return entityLogEntry.filter(entry => {
            entry.positions = entry.positions?.filter(p => !!p.rectangle?.length);
            const hasPositions = !!entry.positions?.length;
            const isRemoved = entry.state === EntryStates.REMOVED;
            if (!hasPositions) {
                this.#toaster.devInfo(`Entry ${entry.id} was skipped because it has no position`);
            }
            return hasPositions && !isRemoved;
        });
    }
}
