import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { EntitiesService, QueryParam } from '@iqser/common-ui';
import { ComponentDefinition, IComponentDefinition } from '@red/domain';
import { List } from '@common-ui/utils';
import { map } from 'rxjs/operators';

@Injectable({
    providedIn: 'root',
})
export class ComponentDefinitionsService extends EntitiesService<IComponentDefinition, ComponentDefinition> {
    getComponentDefinitions(dossierTemplateId: string): Observable<IComponentDefinition[]> {
        return this._http
            .get<IComponentDefinition[]>(`/api/dossier-templates/${dossierTemplateId}/component-definitions`)
            .pipe(map(componentDefinitions => this.#sortComponents(componentDefinitions)));
    }

    createComponentDefinition(dossierTemplateId: string, componentDefinition: IComponentDefinition): Observable<IComponentDefinition[]> {
        return this._http.post<IComponentDefinition[]>(`/api/dossier-templates/${dossierTemplateId}/component-definitions`, [
            componentDefinition,
        ]);
    }

    updateComponentDefinition(dossierTemplateId: string, componentDefinition: IComponentDefinition): Observable<IComponentDefinition[]> {
        return this._http.put<IComponentDefinition[]>(`/api/dossier-templates/${dossierTemplateId}/component-definitions`, [
            componentDefinition,
        ]);
    }

    deleteComponentDefinitions(dossierTemplateId: string, componentIds: string[]): Observable<unknown> {
        const queryParams: List<QueryParam> = [{ key: 'componentIds', value: componentIds.join(',') }];

        return this._http.delete<IComponentDefinition[]>(`/api/dossier-templates/${dossierTemplateId}/component-definitions`, {
            params: this._queryParams(queryParams),
        });
    }

    reorderComponentDefinitions(dossierTemplateId: string, componentIds: string[]): Observable<IComponentDefinition[]> {
        const queryParams: List<QueryParam> = [{ key: 'componentIds', value: componentIds.join(',') }];

        return this._http
            .get<IComponentDefinition[]>(`/api/dossier-templates/${dossierTemplateId}/component-definitions/reorder`, {
                params: this._queryParams(queryParams),
            })
            .pipe(map(componentDefinitions => this.#sortComponents(componentDefinitions)));
    }

    #sortComponents(componentDefinitions: IComponentDefinition[]) {
        return componentDefinitions.sort((a, b) => a.rank - b.rank);
    }
}
