import { GenericService, QueryParam } from '@iqser/common-ui';
import { inject, Injectable } from '@angular/core';
import { HttpEvent, HttpHeaders, HttpResponse } from '@angular/common/http';
import { Observable } from 'rxjs';
import { switchMap } from 'rxjs/operators';
import { FilesService } from './files.service';
import { File, IPageRotationRequest } from '@red/domain';
import { HeadersConfiguration, List } from '@iqser/common-ui/lib/utils';

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

    delete(files: List<File>, dossierId: string) {
        const fileIds = files.map(f => f.id);
        return super._post(fileIds, `delete/${dossierId}`).pipe(switchMap(() => this.#filesService.loadAll(dossierId)));
    }

    rotatePage(body: IPageRotationRequest, dossierId: string, fileId: string) {
        return this._post(body, `rotate/${dossierId}/${fileId}`);
    }

    downloadOriginal(dossierId: string, fileId: string, observe?: 'events', indicator?: string): Observable<HttpEvent<Blob>>;
    downloadOriginal(dossierId: string, fileId: string, observe?: 'response', indicator?: string): Observable<HttpResponse<Blob>>;
    downloadOriginal(dossierId: string, fileId: string, observe: 'events' | 'response' = 'events', indicator?: string) {
        const queryParams: QueryParam[] = [{ key: 'inline', value: true }];

        if (indicator) {
            queryParams.push({ key: 'indicator', value: indicator });
        }

        let headers = new HttpHeaders();
        const httpHeaderAcceptSelected = HeadersConfiguration.selectHeaderAccept(['*/*']);
        if (httpHeaderAcceptSelected !== undefined) {
            headers = headers.set('Accept', httpHeaderAcceptSelected);
        }

        return this._http.request(
            'get',
            `/${this._serviceName}/download/viewer_doc/${encodeURIComponent(dossierId)}/${encodeURIComponent(fileId)}`,
            {
                responseType: 'blob',
                params: this._queryParams(queryParams),
                headers: headers,
                observe: observe,
                reportProgress: observe === 'events',
            },
        );
    }
}
