import React, { useState, useEffect } from 'react'; import PropTypes from 'prop-types'; import { Divider } from '@patternfly/react-core'; import { translate as __ } from 'foremanReact/common/I18n'; import InputField from '../../common/FormInputs'; const NetworkInterface = ({ id, networks, bridges, data, updateNetworkData, existingInterfaces, }) => { const [network, setNetwork] = useState(data); const [error, setError] = useState(''); useEffect(() => { const currentNetData = JSON.stringify(network); const parentNetData = JSON.stringify(data); if (currentNetData !== parentNetData) { updateNetworkData(id, network); } }, [network, id, data, updateNetworkData]); const handleChange = e => { const { name, type, checked, value: targetValue } = e.target; let value; if (type === 'checkbox') { value = checked ? '1' : '0'; } else { value = targetValue; } const updatedKey = Object.keys(network).find( key => network[key].name === name ); const updatedData = { ...network, [updatedKey]: { ...network[updatedKey], value }, }; setNetwork(updatedData); if (updatedKey === 'id') { const idValue = value; if ( Object.values(existingInterfaces).some( net => net.data.id.value === idValue && net.data.id.value !== network.id.value ) ) { setError(__('Error: Duplicate ID found.')); return; } setError(''); } if (updatedKey === 'name') { const idValue = value; if ( Object.values(existingInterfaces).some( net => net.data.id.value === idValue && net.data.id.value !== network.id.value ) ) { setError(__('Error: Duplicate Name found.')); } else { setError(''); } } }; const bridgesMap = bridges.map(bridge => ({ value: bridge.iface, label: bridge.iface, })); return (
= 0, e.g. net0')} type="text" value={network?.id?.value} onChange={handleChange} error={error} /> = 0, e.g. eth0')} type="text" value={network?.name?.value} onChange={handleChange} error={error} />
); }; NetworkInterface.propTypes = { id: PropTypes.number.isRequired, networks: PropTypes.array, bridges: PropTypes.array, data: PropTypes.object, updateNetworkData: PropTypes.func, existingInterfaces: PropTypes.array, }; NetworkInterface.defaultProps = { networks: [], bridges: [], data: {}, updateNetworkData: Function.prototype, existingInterfaces: [], }; export default NetworkInterface;