import { Injectable } from '@angular/core';
import { ComponentLogEntry } from '@red/domain';
import { INestedFilter, NestedFilter } from '@common-ui/filtering';

@Injectable()
export class ComponentLogFilterService {
    filterGroups(entities: ComponentLogEntry[]) {
        const allDistinctComponentLogs = new Set<string>();

        entities?.forEach(entry => allDistinctComponentLogs.add(entry.name));

        const componentLogFilters = [...allDistinctComponentLogs].map(
            id =>
                new NestedFilter({
                    id: id,
                    label: id.replaceAll('_', ' '),
                }),
        );

        return [
            {
                slug: 'componentLogFilters',
                filters: componentLogFilters,
            },
        ];
    }

    filterComponents(components: ComponentLogEntry[], filters: INestedFilter[]) {
        const someFiltersChecked = !!filters.find(f => f.checked);
        if (!someFiltersChecked) {
            return components;
        }

        const checkedFiltersIds = filters.reduce((ids, f) => {
            if (f.checked) {
                ids.push(f.id);
            }
            return ids;
        }, []);

        return components.filter(c => checkedFiltersIds.includes(c.name));
    }
}
