"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getAddress = exports.labelsToArray = exports.allSubnetsIPv6 = exports.allSubnetsIPv4 = exports.getFormikObjectItemFieldName = exports.getFormikArrayItemFieldName = exports.getRichTextValidation = exports.getDuplicates = exports.parseStringLabels = exports.getDefaultOpenShiftVersion = exports.getFormikErrorFields = exports.trimCommaSeparatedList = exports.trimSshPublicKey = exports.getFieldId = void 0;
const tslib_1 = require("tslib");
const ip_address_1 = require("ip-address");
const set_js_1 = tslib_1.__importDefault(require("lodash-es/set.js"));
const groupBy_js_1 = tslib_1.__importDefault(require("lodash-es/groupBy.js"));
const pickBy_js_1 = tslib_1.__importDefault(require("lodash-es/pickBy.js"));
const utils_1 = require("../../../utils");
const getFieldId = (fieldName, fieldType, unique) => {
    unique = unique ? `${unique}-` : '';
    return `form-${fieldType}-${fieldName.replace(/\./g, '-')}-${unique}field`;
};
exports.getFieldId = getFieldId;
const trimSshPublicKey = (key) => key
    .split('\n')
    .map((row) => row.trim())
    .filter(Boolean)
    .join('\n');
exports.trimSshPublicKey = trimSshPublicKey;
const trimCommaSeparatedList = (list) => list
    .split(',')
    .map((item) => item.trim())
    .filter(Boolean)
    .join(',');
exports.trimCommaSeparatedList = trimCommaSeparatedList;
const getFormikErrorFields = (errors, touched) => (0, utils_1.getKeys)(errors).filter((field) => touched[field]);
exports.getFormikErrorFields = getFormikErrorFields;
const getDefaultOpenShiftVersion = (versions) => { var _a, _b; return ((_a = versions.find((v) => v.default)) === null || _a === void 0 ? void 0 : _a.value) || ((_b = versions[0]) === null || _b === void 0 ? void 0 : _b.value) || ''; };
exports.getDefaultOpenShiftVersion = getDefaultOpenShiftVersion;
// strValues: array of 'key=value' items
const parseStringLabels = (strValues) => {
    const labels = strValues.reduce((acc, curr) => {
        const label = curr.split('=');
        acc[label[0]] = label[1];
        return acc;
    }, {});
    return labels;
};
exports.parseStringLabels = parseStringLabels;
const fieldErrorReducer = (errors) => {
    return errors.reduce((memo, { path, message }) => (Object.assign(Object.assign({}, memo), { [path]: (memo[path] || []).concat(message) })), {});
};
const getDuplicates = (list) => {
    const duplicateKeys = (0, pickBy_js_1.default)((0, groupBy_js_1.default)(list), (x) => x.length > 1);
    return Object.keys(duplicateKeys);
};
exports.getDuplicates = getDuplicates;
const getRichTextValidation = (schema) => (values) => tslib_1.__awaiter(void 0, void 0, void 0, function* () {
    try {
        yield schema.validate(values, {
            abortEarly: false,
        });
    }
    catch (e) {
        const { inner } = e;
        if (!inner || inner.length === 0) {
            return {};
        }
        const baseFields = [];
        const arraySubfields = [];
        inner.forEach((item) => {
            const isArraySubfield = /\.|\[/.test(item.path);
            if (isArraySubfield) {
                arraySubfields.push(item);
            }
            else {
                baseFields.push(item);
            }
        });
        const fieldErrors = fieldErrorReducer(baseFields);
        if (arraySubfields.length === 0) {
            return fieldErrors;
        }
        // Now we need to convert the fieldArray errors to the parent object
        // eg. items[0].thumbprint --> { items: [{ thumbprint: ['subField error'] }]}
        const arrayErrors = {};
        arraySubfields.forEach((field) => {
            (0, set_js_1.default)(arrayErrors, field.path, [field.message]);
        });
        return Object.assign(Object.assign({}, fieldErrors), arrayErrors);
    }
});
exports.getRichTextValidation = getRichTextValidation;
const getFormikArrayItemFieldName = (arrayFieldName, idx) => {
    return `${arrayFieldName}[${idx}]`;
};
exports.getFormikArrayItemFieldName = getFormikArrayItemFieldName;
const getFormikObjectItemFieldName = (objectFieldName, idx) => {
    return `${objectFieldName}.${idx}`;
};
exports.getFormikObjectItemFieldName = getFormikObjectItemFieldName;
const allSubnetsIPv4 = (networks) => {
    return !!(networks === null || networks === void 0 ? void 0 : networks.every((network) => network.cidr && ip_address_1.Address4.isValid(network.cidr)));
};
exports.allSubnetsIPv4 = allSubnetsIPv4;
const allSubnetsIPv6 = (networks) => {
    return !!(networks === null || networks === void 0 ? void 0 : networks.every((network) => network.cidr && ip_address_1.Address6.isValid(network.cidr)));
};
exports.allSubnetsIPv6 = allSubnetsIPv6;
const labelsToArray = (labels = {}) => {
    const result = [];
    for (const key in labels) {
        result.push(`${key}=${labels[key]}`);
    }
    return result;
};
exports.labelsToArray = labelsToArray;
const getAddress = (addr) => {
    if (ip_address_1.Address4.isValid(addr)) {
        return new ip_address_1.Address4(addr);
    }
    else if (ip_address_1.Address6.isValid(addr)) {
        return new ip_address_1.Address6(addr);
    }
    return undefined;
};
exports.getAddress = getAddress;
//# sourceMappingURL=utils.js.map