'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 indexedAccesHelper = require('../indexedAccesHelper.js');
var dateHelper = require('../dateHelper.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 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;
};
/**
 * Createa a query string from the saved defaults
 *
 * @param {defaultFilterValue[]} defaults
 * @return {*}  {string}
 */
const createQsFromSavedDefaults = (defaults, fieldDefinitions) => {
    const fieldMap = new Map(fieldDefinitions.map((f) => [f.name, f]));
    return defaults
        .flatMap(({ name, value }) => {
        const keyBase = `filters.${name}`;
        const fieldDef = fieldMap.get(name);
        // --------------------------------------------
        // STRING
        // --------------------------------------------
        if (typeof value === 'string') {
            const isMultiSelect = fieldDef?.filter?.type === 'multiselect';
            if (isMultiSelect) {
                return value
                    .split(',')
                    .map((v) => v.trim())
                    .filter(Boolean)
                    .map((v) => [keyBase, v]);
            }
            return [[keyBase, dateHelper.uiDateToApi(value) || value]];
        }
        // --------------------------------------------
        // GRANULAR DATERANGE
        // --------------------------------------------
        if ('granularity' in value) {
            return [
                [`${keyBase}.start`, dateHelper.uiDateToApi(value.start) || ''],
                [`${keyBase}.end`, dateHelper.uiDateToApi(value.end) || ''],
                [`${keyBase}.granularity`, String(value.granularity)],
                [`${keyBase}.quickFilter`, String(value.quickFilter)],
            ];
        }
        // --------------------------------------------
        // DATE RANGE
        // --------------------------------------------
        const pairs = [
            [`${keyBase}.start`, dateHelper.uiDateToApi(value.start) || ''],
            [`${keyBase}.end`, dateHelper.uiDateToApi(value.end) || ''],
        ];
        if (value.relative !== undefined) {
            pairs.push([`${keyBase}.relative-duration`, value.relative]);
        }
        return pairs;
    })
        .reduce((params, [key, value]) => {
        params.append(key, value);
        return params;
    }, new URLSearchParams())
        .toString();
};
var PersonalisationUtils = { saveDefaults, removeDefaults, setUserContextDefaults };

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