"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.filterFormDataByRole = filterFormDataByRole;
exports.filterFormFieldsData = filterFormFieldsData;
exports.toFormFieldsData = toFormFieldsData;
exports.filterFormFieldsByConfig = filterFormFieldsByConfig;
const logger_1 = require("../../../utils/logger");
const fieldTypeConfigMap = {
    textFields: { allowedKey: 'textFields' },
    comboboxFields: { allowedKey: 'comboboxFields' },
    multiComboboxFields: { allowedKey: 'multiComboboxFields' },
    daDataFields: { allowedKey: 'daDataFields' },
    fileFields: { allowedKey: 'fileFields' },
    checkboxes: { allowedKey: 'checkboxes' },
    toggleButtons: { allowedKey: 'toggleButtons' },
    radioButtons: { allowedKey: 'radioButtons' }
};
function getVisibleFieldNames(fields) {
    return fields?.filter(f => !f.hidden).map(f => f.name) ?? [];
}
function getHiddenFieldNames(fields) {
    return fields?.filter(f => f.hidden).map(f => f.name) ?? [];
}
function filterFormDataByRoleImpl(formData, config, fieldType, loggerContext) {
    const logContext = loggerContext ?? 'FormDataFilterUtils.filterFormDataByRole';
    if (!config) {
        return formData;
    }
    if (fieldType === 'radioButtons') {
        return filterRadioButtons(formData, config, logContext);
    }
    return filterObjectFields(formData, config, fieldType, logContext);
}
function filterRadioButtons(data, config, logContext) {
    const keys = data ?? [];
    const radioConfig = config.radioButtons || [];
    const allowed = getVisibleFieldNames(radioConfig);
    const notVisible = getHiddenFieldNames(radioConfig);
    const filtered = keys.filter(key => {
        if (notVisible.includes(key)) {
            logger_1.logger.debug(`Радио-кнопка ${key} скрыта для роли`, logContext);
            return false;
        }
        if (!allowed.includes(key)) {
            logger_1.logger.debug(`Радио-кнопка ${key} не указана в конфигурации`, logContext);
            return false;
        }
        return true;
    });
    return filtered.length === 0 ? undefined : filtered;
}
function filterObjectFields(data, config, fieldType, logContext) {
    const typeConfig = fieldTypeConfigMap[fieldType];
    const fieldConfig = config[typeConfig.allowedKey];
    const allowedFields = getVisibleFieldNames(fieldConfig);
    const notVisibleFields = getHiddenFieldNames(fieldConfig);
    const filteredData = {};
    for (const [key, value] of Object.entries(data)) {
        if (notVisibleFields.includes(key)) {
            logger_1.logger.debug(`Поле ${key} пропущено, т.к. оно скрыто для роли`, logContext);
            continue;
        }
        if (!allowedFields.includes(key)) {
            logger_1.logger.debug(`Поле ${key} пропущено, т.к. оно не указано в конфигурации`, logContext);
            continue;
        }
        if (!isValidValueForFieldType(value, fieldType)) {
            logger_1.logger.debug(`Поле ${key} имеет неверный тип для ${fieldType}`, logContext);
            continue;
        }
        filteredData[key] = value;
    }
    return Object.keys(filteredData).length > 0 ? filteredData : {};
}
function isValidValueForFieldType(value, fieldType) {
    switch (fieldType) {
        case 'textFields':
            return typeof value === 'string';
        case 'fileFields':
            return Array.isArray(value) && value.every(v => typeof v === 'string');
        case 'comboboxFields':
            return isSelectValue(value);
        case 'checkboxes':
            return typeof value === 'boolean';
        case 'toggleButtons':
            return typeof value === 'boolean' || value === 'Yes' || value === 'No';
        case 'multiComboboxFields':
            return Array.isArray(value) && value.every(isSelectValue);
        case 'daDataFields':
            return isDaDataValue(value);
        default:
            return true;
    }
}
function isSelectValue(value) {
    return (typeof value === 'object' &&
        value !== null &&
        'selectValue' in value &&
        typeof value.selectValue === 'string');
}
function isDaDataValue(value) {
    if (!isSelectValue(value))
        return false;
    const daDataValue = value;
    return daDataValue.expectedValue === undefined || typeof daDataValue.expectedValue === 'string';
}
function filterFormDataByRole(formData, config, fieldType, loggerContext) {
    return filterFormDataByRoleImpl(formData, config, fieldType, loggerContext);
}
function filterFormFieldsData(formFields, config, loggerContext) {
    const logCtx = loggerContext ?? 'FormDataFilterUtils.filterFormFieldsData';
    if (!config) {
        throw new Error('Не удалось отфильтровать FormFieldsData по конфигурации. Похоже она отсутствует.');
    }
    return {
        filteredTextFieldsData: formFields.textFieldsData
            ? filterFormDataByRole(formFields.textFieldsData, config, 'textFields', logCtx)
            : undefined,
        filteredComboboxFieldsData: formFields.comboboxFieldsData
            ? filterFormDataByRole(formFields.comboboxFieldsData, config, 'comboboxFields', logCtx)
            : undefined,
        filteredFileFieldsData: formFields.fileFieldsData
            ? filterFormDataByRole(formFields.fileFieldsData, config, 'fileFields', logCtx)
            : undefined,
        filteredRadioButtonsData: formFields.radioButtonsData
            ? filterFormDataByRole(formFields.radioButtonsData, config, 'radioButtons', logCtx)
            : undefined,
        filteredCheckboxesData: formFields.checkboxesData
            ? filterFormDataByRole(formFields.checkboxesData, config, 'checkboxes', logCtx)
            : undefined,
        filteredToggleButtonsData: formFields.toggleButtonsData
            ? filterFormDataByRole(formFields.toggleButtonsData, config, 'toggleButtons', logCtx)
            : undefined,
        filteredDaDataFieldsData: formFields.daDataFieldsData
            ? filterFormDataByRole(formFields.daDataFieldsData, config, 'daDataFields', logCtx)
            : undefined,
        filteredMultiComboboxFieldsData: formFields.multiComboboxFieldsData
            ? filterFormDataByRole(formFields.multiComboboxFieldsData, config, 'multiComboboxFields', logCtx)
            : undefined,
    };
}
function toFormFieldsData(filteredFields) {
    return {
        textFieldsData: filteredFields.filteredTextFieldsData,
        comboboxFieldsData: filteredFields.filteredComboboxFieldsData,
        fileFieldsData: filteredFields.filteredFileFieldsData,
        radioButtonsData: filteredFields.filteredRadioButtonsData,
        checkboxesData: filteredFields.filteredCheckboxesData,
        toggleButtonsData: filteredFields.filteredToggleButtonsData,
        daDataFieldsData: filteredFields.filteredDaDataFieldsData,
        multiComboboxFieldsData: filteredFields.filteredMultiComboboxFieldsData,
    };
}
function filterFormFieldsByConfig(formFields, config, loggerContext) {
    if (!config) {
        throw new Error('Не удалось отфильтровать FormFieldsData по конфигурации. Похоже она отсутствует.');
    }
    return toFormFieldsData(filterFormFieldsData(formFields, config, loggerContext));
}
