'use strict';

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

var _enum = require('./filter-input/enum.js');
var utils = require('./filters-selected/utils.js');
var utils$5 = require('../_inputs/date-range/utils.js');
var utils$3 = require('../_inputs/date-input/utils.js');
var utils$4 = require('../_inputs/granular-date-range/utils.js');
var utils$1 = require('../_inputs/autocomplete-text-input/utils.js');
var utils$2 = require('../_inputs/multi-select/utils.js');
var personalisationUtils = require('../../utils/Personalisation/personalisationUtils.js');
var filtersTypeEnum = require('./filtersTypeEnum.js');
var localsHelper = require('../../utils/localsHelper.js');

/**
 * Given a FilterValue[], will update the values to match the req.query values if present
 *
 * @param {FilterValue[]} filters
 * @param {Request} req
 * @param {string} [prefix='filters.']
 * @return {*}  {FilterValue[]}
 */
const setFilterValuesFromRequest = (filters, req, prefix = 'filters.') => {
    const { preventDefault } = req.query;
    if (Object.keys(req.query).every((key) => !key.includes(prefix)) && !preventDefault) {
        return filters;
    }
    return filters.map((filter) => {
        let requestfilterValue;
        let requestfilterValues;
        let requestOptionValue;
        const type = filter.type.toLowerCase();
        switch (type) {
            case _enum.FilterType.dateRange.toLowerCase():
                requestfilterValue = utils$5.default.setValueFromRequest(filter, req, prefix);
                break;
            case _enum.FilterType.granularDateRange.toLowerCase():
                requestfilterValue = utils$4.default.setValueFromRequest(filter, req, prefix);
                break;
            case _enum.FilterType.date.toLowerCase():
                requestfilterValue = utils$3.default.setValueFromRequest(filter, req, prefix);
                break;
            case _enum.FilterType.multiselect.toLowerCase():
                ({ requestfilterValue, requestfilterValues } = utils$2.default.setValueFromRequest(filter, req, prefix));
                break;
            case _enum.FilterType.autocomplete.toLowerCase(): {
                ({ requestfilterValue, requestOptionValue } = utils$1.setValueFromRequest(filter, req, prefix));
                break;
            }
            default:
                requestfilterValue = req.query[`${prefix}${filter.name}`];
                break;
        }
        let value = null;
        if (requestfilterValue) {
            value = requestfilterValue;
        }
        else if (preventDefault) {
            value = '';
        }
        return {
            ...filter,
            value,
            ...(requestfilterValues && { values: requestfilterValues }),
            ...(requestOptionValue && { staticOptionNameValue: requestOptionValue }),
        };
    });
};
const getFiltersFromDefinition = (fields, interactive) => {
    const filters = fields
        .filter((f) => f.filter)
        .filter((f) => {
        if (interactive !== undefined) {
            if (f.filter?.interactive === undefined) {
                return !interactive;
            }
            return interactive === f.filter.interactive;
        }
        return true;
    })
        .map((f) => {
        const { display: text, name } = f;
        const filter = f.filter;
        const { type, staticOptions, dynamicOptions, defaultValue, mandatory, pattern, index } = filter;
        const options = staticOptions
            ? staticOptions.map((opt) => {
                return { value: opt.name, text: opt.display };
            })
            : [];
        let filterData = {
            text,
            name,
            type: type,
            value: defaultValue || null,
            mandatory: mandatory || false,
            minimumLength: dynamicOptions?.minimumLength,
            pattern,
            index,
        };
        const noFilterOption = {
            value: 'no-filter',
            text: 'None',
            disabled: false,
        };
        switch (type) {
            case _enum.FilterType.autocomplete.toLowerCase():
                filterData = {
                    ...filterData,
                    options,
                };
                break;
            case _enum.FilterType.radio:
                if (!mandatory)
                    options.unshift(noFilterOption);
                filterData = {
                    ...filterData,
                    options,
                };
                break;
            case _enum.FilterType.select: {
                if (!mandatory)
                    options.unshift(noFilterOption);
                options.unshift({
                    value: '',
                    text: 'Select your option',
                    disabled: true,
                    selected: true,
                });
                filterData = {
                    ...filterData,
                    options,
                };
                break;
            }
            case _enum.FilterType.multiselect.toLowerCase():
                filterData = {
                    ...filterData,
                    options,
                    values: defaultValue ? defaultValue.split(',') : [],
                };
                break;
            case _enum.FilterType.dateRange.toLowerCase():
                filterData = utils$5.default.getFilterFromDefinition(filter, filterData);
                break;
            case _enum.FilterType.date.toLowerCase():
                filterData = utils$3.default.getFilterFromDefinition(filter, filterData);
                break;
            case _enum.FilterType.granularDateRange.toLocaleLowerCase(): {
                filterData = utils$4.default.getFilterFromDefinition(filter, filterData);
                break;
            }
        }
        return filterData;
    });
    const orderedFilters = orderFilters(filters);
    return orderedFilters;
};
const orderFilters = (filterValues) => {
    const noIndexFilters = filterValues.filter((f) => f.index === undefined);
    const indexFilters = filterValues.filter((f) => f.index !== undefined);
    indexFilters.forEach((f) => {
        if (f.index !== undefined)
            noIndexFilters.splice(f.index, 0, f);
    });
    return noIndexFilters;
};
const setRequestQueryFromFilterValues = (filterValues, verbose = false) => {
    const requestQuery = filterValues
        .filter((fv) => fv.value)
        .reduce((acc, curr) => {
        const { value, name, type } = curr;
        const filterPrefix = `filters.${name}`;
        switch (type) {
            case _enum.FilterType.granularDateRange.toLowerCase():
                {
                    const granularDateRangeValue = value;
                    Object.keys(granularDateRangeValue).forEach((key) => {
                        let v = granularDateRangeValue[key];
                        if (key.includes('partialDate')) {
                            acc = {
                                ...acc,
                            };
                        }
                        else {
                            if (key.includes('granularity') || key.includes('quickFilter')) {
                                v = v.value;
                            }
                            acc = {
                                ...acc,
                                [`${filterPrefix}.${key}`]: v,
                            };
                        }
                    });
                }
                break;
            case _enum.FilterType.dateRange.toLowerCase():
                if (value) {
                    Object.keys(value).forEach((key) => {
                        const attrKey = !verbose && key.includes('relative') ? undefined : `${filterPrefix}.${key}`;
                        const attrValue = value[key];
                        if (attrKey) {
                            acc = {
                                ...acc,
                                [`${attrKey}`]: attrValue,
                            };
                        }
                    });
                }
                break;
            case _enum.FilterType.multiselect.toLowerCase():
                acc = {
                    ...acc,
                    [`${filterPrefix}`]: value.split(','),
                };
                break;
            default:
                acc = {
                    ...acc,
                    [`${filterPrefix}`]: value,
                };
                break;
        }
        return acc;
    }, {});
    return requestQuery;
};
const getPersonalisedFilters = async (filters, req, res, services, filtersType) => {
    const { reportId, id } = req.params;
    const { dprUser } = localsHelper.default.getValues(res);
    const defaultFilterValues = await services.defaultFilterValuesService.get(dprUser.id, reportId, id, filtersType);
    let defaultFilters = filters;
    if (defaultFilterValues) {
        const personalisedFilters = personalisationUtils.default.setFilterValuesFromSavedDefaults(filters, [], defaultFilterValues);
        defaultFilters = personalisedFilters.filters;
    }
    return { filters: defaultFilters, defaultFilterValues };
};
const getFilters = async ({ fields, req, res, prefix = 'filters.', services, filtersType, }) => {
    // 1. Set the filters from the product definition
    let filters = await getFiltersFromDefinition(fields, filtersType === filtersTypeEnum.FiltersType.INTERACTIVE);
    let hasDefaults;
    let canSaveDefaults = false;
    if (services && res && res.locals['saveDefaultsEnabled']) {
        // 2. If there are personalised filters, overwrite fiters with the personalised filter values.
        const { filters: personalisedFilterValues, defaultFilterValues } = await getPersonalisedFilters(filters, req, res, services, filtersType);
        filters = personalisedFilterValues;
        hasDefaults = defaultFilterValues && defaultFilterValues.length > 0;
        canSaveDefaults = true;
    }
    // If there is a request query, overwrite the filters with the query params
    if (req.query) {
        filters = setFilterValuesFromRequest(filters, req);
    }
    // Set the selected filters
    const selectedFilters = utils.default.getSelectedFilters(filters, prefix);
    return {
        filters,
        selectedFilters,
        hasDefaults,
        canSaveDefaults,
    };
};
var FiltersUtils = {
    getFiltersFromDefinition,
    setFilterValuesFromRequest,
    getFilters,
    setRequestQueryFromFilterValues,
    getPersonalisedFilters,
};

exports.default = FiltersUtils;
exports.getFilters = getFilters;
exports.getFiltersFromDefinition = getFiltersFromDefinition;
exports.getPersonalisedFilters = getPersonalisedFilters;
exports.setFilterValuesFromRequest = setFilterValuesFromRequest;
exports.setRequestQueryFromFilterValues = setRequestQueryFromFilterValues;
//# sourceMappingURL=utils.js.map
