import { Injectable } from '@angular/core';
import { GenericService } from '@iqser/common-ui';
import { catchError, map } from 'rxjs/operators';
import { IViewedPage, IViewedPagesRequest, ViewedPage } from '@red/domain';
import { firstValueFrom, of } from 'rxjs';
import { mapEach } from '@iqser/common-ui/lib/utils';

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

    add(body: IViewedPagesRequest, dossierId: string, fileId: string) {
        const modelPath = `${this._defaultModelPath}/${dossierId}/${fileId}`;
        return firstValueFrom(this._post(body, modelPath));
    }

    remove(dossierId: string, fileId: string, page: number) {
        const modelPath = `${this._defaultModelPath}/${dossierId}/${fileId}/${page}`;
        return firstValueFrom(super.delete({}, modelPath));
    }

    load(dossierId: string, fileId: string) {
        const request = this._getOne<{ pages?: IViewedPage[] }>([dossierId, fileId]).pipe(
            map(res => res.pages),
            catchError(() => of([] as IViewedPage[])),
            mapEach(page => new ViewedPage(page)),
        );

        return firstValueFrom(request);
    }
}
