import { isIPNetworkValid } from "../../utils/FormUtils";
import { TextInput } from "./TextInput";

function rebuildNetworksList(val?: string): string[] | undefined {
  if (!val || val.trim() === "") return undefined;

  return val.split(",").map((v) => v.trim());
}

export function NetworksInput(p: {
  editable?: boolean;
  label: string;
  value?: string[];
  onChange: (n: string[] | undefined) => void;
}): React.ReactElement {
  const textValue = (p.value ?? []).join(", ").trim();
  return (
    <TextInput
      {...p}
      type="string"
      value={textValue}
      onValueChange={(i) => p.onChange(rebuildNetworksList(i))}
      checkValue={(v) => (rebuildNetworksList(v) ?? []).every(isIPNetworkValid)}
    />
  );
}
