'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

var localsHelper = require('../localsHelper.js');
var UserReports = require('../../types/UserReports.js');
var _enum = require('../../components/_filters/filter-input/enum.js');
var utils$1 = require('../../components/_inputs/date-range/utils.js');
var utils = require('../../components/_inputs/granular-date-range/utils.js');
var utils$3 = require('../../components/_inputs/multi-select/utils.js');
var utils$2 = require('../../components/_inputs/date-input/utils.js');
var indexedAccesHelper = require('../indexedAccesHelper.js');

const saveDefaults = async (type, res, req, services) => {
    const defaultValuesForReport = await getDefaultValues(req, res, services, type);
    const { dprUser } = localsHelper.default.getValues(res);
    const id = indexedAccesHelper.getRequestParam({ req, param: 'id' });
    const reportId = indexedAccesHelper.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.default.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.default.getValues(res);
    const { reportId, id, type } = req.params;
    let definition;
    let fields = [];
    if (type === UserReports.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 _enum.FilterType.multiselect.toLocaleLowerCase():
                    value = Array.isArray(k.value) ? k.value.join(',') : k.value;
                    break;
                case _enum.FilterType.dateRange.toLocaleLowerCase():
                    ({ value, name } = utils$1.default.setDefaultValue(req, name));
                    break;
                case _enum.FilterType.granularDateRange.toLocaleLowerCase():
                    ({ name, value } = utils.default.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 _enum.FilterType.multiselect.toLocaleLowerCase():
                updatedFilter = utils$3.default.setFilterValuesFromSavedDefault(updatedFilter, hasDefaults, defaultValue);
                break;
            case _enum.FilterType.date.toLocaleLowerCase():
                if (hasDefaults) {
                    updatedFilter.value = '';
                }
                if (defaultValue) {
                    updatedFilter = utils$2.default.setFilterValueFromDefault(defaultValue, updatedFilter);
                }
                break;
            case _enum.FilterType.dateRange.toLocaleLowerCase():
                if (hasDefaults) {
                    updatedFilter.value = { start: '', end: '', relative: undefined };
                }
                if (defaultValue) {
                    updatedFilter = (utils$1.default.setFilterValueFromDefault(defaultValue, updatedFilter));
                }
                break;
            case _enum.FilterType.granularDateRange.toLocaleLowerCase():
                if (hasDefaults) {
                    updatedFilter.value = { start: '', end: '', granularity: undefined, quickFilter: undefined };
                }
                if (defaultValue) {
                    updatedFilter = (utils.default.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.default.getValues(res);
    const { activeCaseLoadId } = dprUser;
    filters.forEach((filter) => {
        if (filter.type.toLocaleLowerCase() === _enum.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 };

exports.default = PersonalisationUtils;
exports.removeDefaults = removeDefaults;
exports.saveDefaults = saveDefaults;
exports.setFilterValuesFromSavedDefaults = setFilterValuesFromSavedDefaults;
exports.setUserContextDefaults = setUserContextDefaults;
//# sourceMappingURL=personalisationUtils.js.map
