import localsHelper from '../localsHelper.js';
import { ReportType } from '../../types/UserReports.js';
import { FilterType } from '../../components/_filters/filter-input/enum.js';
import DateRangeInputUtils from '../../components/_inputs/date-range/utils.js';
import GranularDateRangeInputUtils from '../../components/_inputs/granular-date-range/utils.js';
import MultiSelectUtils from '../../components/_inputs/multi-select/utils.js';
import DateInputUtils from '../../components/_inputs/date-input/utils.js';
import { getRequestParam } from '../indexedAccesHelper.js';

const saveDefaults = async (type, res, req, services) => {
    const defaultValuesForReport = await getDefaultValues(req, res, services, type);
    const { dprUser } = localsHelper.getValues(res);
    const id = getRequestParam({ req, param: 'id' });
    const reportId = getRequestParam({ req, param: 'reportId' });
    const { defaultFilterValuesService } = services;
    return defaultFilterValuesService
        ? defaultFilterValuesService.save(dprUser.id, reportId, id, defaultValuesForReport)
        : undefined;
};
const removeDefaults = async (type, res, req, services) => {
    const { dprUser } = localsHelper.getValues(res);
    const { reportId, id } = req.params;
    const { defaultFilterValuesService } = services;
    return defaultFilterValuesService ? defaultFilterValuesService.delete(dprUser.id, reportId, id, type) : undefined;
};
const getDefaultValues = async (req, res, services, filtersType) => {
    const { token, definitionsPath } = localsHelper.getValues(res);
    const { reportId, id, type } = req.params;
    let definition;
    let fields = [];
    if (type === ReportType.REPORT) {
        definition = await services.reportingService.getDefinition(token, reportId, id, definitionsPath);
        fields = definition.variant.specification?.fields || [];
    }
    else {
        definition = await services.dashboardService.getDefinition(token, reportId, id, definitionsPath);
        fields = definition.filterFields || [];
    }
    const bodyFilterValues = Object.keys(req.body)
        .filter((k) => {
        return k.includes('filters.') || k.includes('sortColumn') || k.includes('sortedAsc');
    })
        .map((k) => {
        return { name: k.replace('filters.', ''), value: req.body[k] };
    })
        .map((k) => {
        const n = k.name.split('.')[0];
        const field = fields.find((f) => f.name === n);
        let { value, name } = k;
        if (field) {
            const filterType = field.filter?.type.toLocaleLowerCase();
            switch (filterType) {
                case FilterType.multiselect.toLocaleLowerCase():
                    value = Array.isArray(k.value) ? k.value.join(',') : k.value;
                    break;
                case FilterType.dateRange.toLocaleLowerCase():
                    ({ value, name } = DateRangeInputUtils.setDefaultValue(req, name));
                    break;
                case FilterType.granularDateRange.toLocaleLowerCase():
                    ({ name, value } = GranularDateRangeInputUtils.setDefaultValue(req, name));
                    break;
            }
        }
        return {
            name,
            value,
            type: filtersType,
        };
    });
    const defaultValuesConfig = Array.from(new Set(bodyFilterValues.map((a) => a.name)))
        .map((name) => {
        return bodyFilterValues.find((a) => a.name === name);
    })
        .filter((c) => c !== undefined);
    const result = defaultValuesConfig.filter((defaultValue) => {
        return defaultValue ? defaultValue.value !== '' : false;
    });
    return result;
};
const setFilterValuesFromSavedDefaults = (filters, sortBy, defaultValues) => {
    const hasDefaults = filters.some((f) => {
        const defaultValue = defaultValues.findIndex((v) => v.name === f.name);
        return defaultValue !== -1;
    });
    const filterValues = filters.map((filter) => {
        const defaultValue = defaultValues.find((v) => v.name === filter.name);
        let updatedFilter = {
            ...filter,
        };
        const type = filter.type.toLocaleLowerCase();
        switch (type) {
            case FilterType.multiselect.toLocaleLowerCase():
                updatedFilter = MultiSelectUtils.setFilterValuesFromSavedDefault(updatedFilter, hasDefaults, defaultValue);
                break;
            case FilterType.date.toLocaleLowerCase():
                if (hasDefaults) {
                    updatedFilter.value = '';
                }
                if (defaultValue) {
                    updatedFilter = DateInputUtils.setFilterValueFromDefault(defaultValue, updatedFilter);
                }
                break;
            case FilterType.dateRange.toLocaleLowerCase():
                if (hasDefaults) {
                    updatedFilter.value = { start: '', end: '', relative: undefined };
                }
                if (defaultValue) {
                    updatedFilter = (DateRangeInputUtils.setFilterValueFromDefault(defaultValue, updatedFilter));
                }
                break;
            case FilterType.granularDateRange.toLocaleLowerCase():
                if (hasDefaults) {
                    updatedFilter.value = { start: '', end: '', granularity: undefined, quickFilter: undefined };
                }
                if (defaultValue) {
                    updatedFilter = (GranularDateRangeInputUtils.setFilterValueFromDefault(defaultValue, updatedFilter));
                }
                break;
            default:
                {
                    let value = hasDefaults ? '' : updatedFilter.value;
                    value = defaultValue ? defaultValue.value : value;
                    updatedFilter = {
                        ...filter,
                        value,
                    };
                }
                break;
        }
        return updatedFilter;
    });
    const sortValues = sortBy.map((sortFilter) => {
        const defaultValue = defaultValues.find((v) => v.name === sortFilter.name);
        return {
            ...sortFilter,
            ...(defaultValue && { value: defaultValue.value }),
        };
    });
    return {
        filters: filterValues,
        sortBy: sortValues,
    };
};
const setUserContextDefaults = (res, filters) => {
    const { dprUser } = localsHelper.getValues(res);
    const { activeCaseLoadId } = dprUser;
    filters.forEach((filter) => {
        if (filter.type.toLocaleLowerCase() === FilterType.autocomplete.toLocaleLowerCase() &&
            filter.text.toLocaleLowerCase().includes('establishment') &&
            activeCaseLoadId?.length) {
            const f = filter;
            const option = f.options.find((opt) => opt.value === activeCaseLoadId);
            if (option) {
                f.value = option.text;
                f.staticOptionNameValue = activeCaseLoadId;
            }
        }
    });
    return filters;
};
var PersonalisationUtils = { saveDefaults, removeDefaults, setFilterValuesFromSavedDefaults, setUserContextDefaults };

export { PersonalisationUtils as default, removeDefaults, saveDefaults, setFilterValuesFromSavedDefaults, setUserContextDefaults };
//# sourceMappingURL=personalisationUtils.js.map
