import { EntitiesService } from '@iqser/common-ui';
import { computed, Injectable, signal } from '@angular/core';
import { BehaviorSubject, Observable, of } from 'rxjs';
import { catchError, tap } from 'rxjs/operators';
import { FileAttributeConfig, FileAttributes, IFileAttributeConfig, IFileAttributesConfig } from '@red/domain';
import { List } from '@iqser/common-ui/lib/utils';

export type FileAttributesConfigMap = Readonly<Record<string, IFileAttributesConfig>>;

@Injectable({
    providedIn: 'root',
})
export class FileAttributesService extends EntitiesService<IFileAttributeConfig, FileAttributeConfig> {
    readonly fileAttributesConfig$ = new BehaviorSubject<FileAttributesConfigMap>({});
    readonly isEditingFileAttribute = computed(() => this.openAttributeEdits().length > 0);

    readonly openAttributeEdits = signal([]);
    readonly openAttributeEdit = signal('');
    readonly fileEdit = signal('');

    protected readonly _defaultModelPath = 'fileAttributes';
    protected readonly _entityClass = FileAttributeConfig;

    setOpenAttributeEdit(attributeId: string) {
        this.openAttributeEdit.set(attributeId);
    }

    setFileEdit(fileId: string) {
        this.fileEdit.set(fileId);
    }

    resetEdit() {
        this.openAttributeEdits.set([]);
        this.fileEdit.set('');
        this.openAttributeEdit.set('');
    }
    /**
     * Get the file attributes that can be used at importing csv.
     */

    loadFileAttributesConfig(dossierTemplateId: string): Observable<IFileAttributesConfig> {
        const request$ = this._getOne<IFileAttributesConfig>(['config', dossierTemplateId]);
        return request$.pipe(
            tap(entities => entities.fileAttributeConfigs.sort((c1, c2) => c1.placeholder.localeCompare(c2.placeholder))),
            tap(entities =>
                this.fileAttributesConfig$.next({
                    ...this.fileAttributesConfig$.value,
                    [dossierTemplateId]: entities,
                }),
            ),
            catchError(() => of({})),
        );
    }

    getFileAttributeConfig(dossierTemplateId: string): IFileAttributesConfig | undefined {
        return this.fileAttributesConfig$.value[dossierTemplateId];
    }

    /**
     * Add or update a file attribute that can be used at importing csv.
     */

    setFileAttributesConfig(body: IFileAttributeConfig, dossierTemplateId: string) {
        const url = `${this._defaultModelPath}/config/fileAttribute/${dossierTemplateId}`;
        return this._post<unknown>(body, url);
    }

    /**
     * Set file attributes base configuration and a list of file attributes,
     */

    setFileAttributeConfig(body: IFileAttributesConfig, dossierTemplateId: string) {
        const url = `${this._defaultModelPath}/config/baseConfig/${dossierTemplateId}`;
        return this._put<unknown>(body, url);
    }

    /**
     * Set file attributes to an existing file
     */

    setFileAttributes(body: FileAttributes, dossierId: string, fileId: string) {
        const url = `${this._defaultModelPath}/set/${dossierId}/${fileId}`;
        return this._post<unknown>(body, url);
    }

    /**
     * Delete a specific file attribute.
     */

    deleteFileAttributes(body: List, dossierTemplateId: string) {
        const url = `${this._defaultModelPath}/config/fileAttribute/${dossierTemplateId}/delete`;
        return this._post(body, url);
    }
}
