import { EntitiesService } from '@iqser/common-ui';
import { DashboardStats, IDashboardStats } from '@red/domain';
import { inject, Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { map, switchMap, tap } from 'rxjs/operators';
import { DossierStatesService } from '../entity-services/dossier-states.service';
import { mapEach } from '@iqser/common-ui/lib/utils';

const templatesSorter = (a: DashboardStats, b: DashboardStats) => {
    if (!a.isEmpty && b.isEmpty) {
        return -1;
    } else if (a.isEmpty && !b.isEmpty) {
        return 1;
    }
    return 0;
};

@Injectable({
    providedIn: 'root',
})
export class DashboardStatsService extends EntitiesService<IDashboardStats, DashboardStats> {
    readonly #dossierStatesService = inject(DossierStatesService);
    protected readonly _defaultModelPath = 'dossier-template/stats';
    protected readonly _entityClass = DashboardStats;

    loadAll(): Observable<DashboardStats[]> {
        return this.getAll(this._defaultModelPath).pipe(
            mapEach(entity => new DashboardStats(entity)),
            switchMap(entities => this.#dossierStatesService.loadAllForAllTemplates().pipe(map(() => entities))),
            tap(entities => entities.sort(templatesSorter)),
            tap(entities => this.setEntities(entities)),
        );
    }
}
