"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.SubnetsDropdown = void 0;
const tslib_1 = require("tslib");
const react_1 = tslib_1.__importDefault(require("react"));
const react_core_1 = require("@patternfly/react-core");
const formik_1 = require("formik");
const ip_address_1 = require("ip-address");
const ui_1 = require("../../ui");
const config_1 = require("../../../config");
const ui_2 = require("../../ui");
const toFormSelectOptions = (subnets) => {
    return subnets.map((hn, index) => ({
        label: `${hn.humanized}${hn.isValid ? '' : ' (Invalid network)'}`,
        value: hn.subnet,
        isDisabled: false,
        id: `form-input-hostSubnet-field-option-${index}`,
    }));
};
const makeNoSubnetSelectedOption = (availableSubnets) => ({
    label: `Please select a subnet. (${availableSubnets} available)`,
    value: config_1.NO_SUBNET_SET,
    isDisabled: true,
    id: 'form-input-hostSubnet-field-option-no-subnet-selected',
});
const noSubnetAvailableOption = {
    label: 'No subnets are currently available',
    value: config_1.NO_SUBNET_SET,
    isDisabled: true,
    id: 'form-input-hostSubnet-field-option-no-subnet-available',
};
const SubnetsDropdown = (_a) => {
    var { name, machineSubnets, isDisabled, onAfterSelect } = _a, props = tslib_1.__rest(_a, ["name", "machineSubnets", "isDisabled", "onAfterSelect"]);
    const [field, , { setValue }] = (0, formik_1.useField)(name);
    const [isOpen, setOpen] = react_1.default.useState(false);
    const fieldId = (0, ui_1.getFieldId)(name, 'input');
    const { itemsSubnets, ipv4Subnets, ipv6Subnets, currentDisplayValue } = react_1.default.useMemo(() => {
        const itemsSubnets = machineSubnets.length === 0
            ? [noSubnetAvailableOption]
            : [makeNoSubnetSelectedOption(machineSubnets.length)].concat(toFormSelectOptions(machineSubnets));
        // Separate IPv4 and IPv6 subnets
        const ipv4Subnets = machineSubnets.filter((subnet) => ip_address_1.Address4.isValid(subnet.subnet));
        const ipv6Subnets = machineSubnets.filter((subnet) => ip_address_1.Address6.isValid(subnet.subnet));
        let currentDisplayValue = itemsSubnets.length > 1 ? itemsSubnets[1].label : itemsSubnets[0].label; // The placeholder is the fallback in some cases
        if (field.value) {
            const subnetItem = itemsSubnets.find((item) => item.value === field.value);
            if (subnetItem) {
                currentDisplayValue = subnetItem.label;
            }
        }
        else if (machineSubnets.length === 1) {
            // When there is only one subnet, it's selected by default. We skip the placeholder at index 0.
            currentDisplayValue = itemsSubnets[1].label;
        }
        return { itemsSubnets, ipv4Subnets, ipv6Subnets, currentDisplayValue: currentDisplayValue };
    }, [machineSubnets, field.value]);
    const dropdownItems = react_1.default.useMemo(() => {
        if (machineSubnets.length === 0) {
            return [
                react_1.default.createElement(react_core_1.DropdownItem, { key: noSubnetAvailableOption.value, id: noSubnetAvailableOption.value, isDisabled: noSubnetAvailableOption.isDisabled, value: noSubnetAvailableOption.value }, noSubnetAvailableOption.label),
            ];
        }
        const hasIpv4 = ipv4Subnets.length > 0;
        const hasIpv6 = ipv6Subnets.length > 0;
        // If we have both IPv4 and IPv6, group them
        if (hasIpv4 && hasIpv6) {
            const ipv4Items = toFormSelectOptions(ipv4Subnets).map(({ value, label, isDisabled }) => (react_1.default.createElement(react_core_1.DropdownItem, { key: value, id: value, isDisabled: isDisabled, value: value }, label)));
            ipv4Items.push(react_1.default.createElement(react_core_1.Divider, { key: "ipv4-divider" }));
            const ipv6Items = toFormSelectOptions(ipv6Subnets).map(({ value, label, isDisabled }) => (react_1.default.createElement(react_core_1.DropdownItem, { key: value, id: value, isDisabled: isDisabled, value: value }, label)));
            return [
                react_1.default.createElement(react_core_1.DropdownItem, { key: makeNoSubnetSelectedOption(machineSubnets.length).value, id: makeNoSubnetSelectedOption(machineSubnets.length).value, isDisabled: makeNoSubnetSelectedOption(machineSubnets.length).isDisabled, value: makeNoSubnetSelectedOption(machineSubnets.length).value }, makeNoSubnetSelectedOption(machineSubnets.length).label),
                react_1.default.createElement(react_core_1.DropdownGroup, { label: "IPv4", key: "ipv4-group" }, ipv4Items),
                react_1.default.createElement(react_core_1.DropdownGroup, { label: "IPv6 (Technology Preview)", key: "ipv6-group" }, ipv6Items),
            ];
        }
        // If only one type, don't group
        return itemsSubnets.map(({ value, label, isDisabled }) => (react_1.default.createElement(react_core_1.DropdownItem, { key: value, id: value, isDisabled: isDisabled, value: value }, label)));
    }, [machineSubnets, ipv4Subnets, ipv6Subnets, itemsSubnets]);
    const onSelect = (event) => {
        const nextValue = event === null || event === void 0 ? void 0 : event.currentTarget.id;
        setValue(nextValue);
        setOpen(false);
        if (onAfterSelect && nextValue) {
            onAfterSelect(nextValue);
        }
    };
    const currentItem = itemsSubnets.find((i) => i.label === currentDisplayValue);
    const isPrimaryMachineNetwork = name === 'machineNetworks.0.cidr';
    const showBadge = Boolean(isPrimaryMachineNetwork && currentItem && ip_address_1.Address6.isValid(currentItem.value));
    const toggle = (toggleRef) => (react_1.default.createElement(react_core_1.MenuToggle, Object.assign({ ref: toggleRef, onClick: () => setOpen(!isOpen), isExpanded: isOpen, isDisabled: isDisabled, id: fieldId, className: "pf-v6-u-w-100", style: { minWidth: '100%' } }, props),
        currentDisplayValue,
        showBadge && (react_1.default.createElement("span", { onClick: (e) => e.stopPropagation() },
            react_1.default.createElement(ui_2.TechnologyPreview, { position: ui_2.PreviewBadgePosition.inlineRight })))));
    return (react_1.default.createElement(react_core_1.Dropdown, Object.assign({}, field, { id: `${fieldId}-dropdown`, onOpenChange: (isOpen) => setOpen(isOpen), onSelect: onSelect, toggle: toggle, isOpen: isOpen }), dropdownItems));
};
exports.SubnetsDropdown = SubnetsDropdown;
//# sourceMappingURL=SubnetsDropdown.js.map