import { TextInput } from "./TextInput";

export function PortInput(p: {
  editable: boolean;
  label: string;
  value?: number;
  onChange: (value: number | undefined) => void;
}): React.ReactElement {
  return (
    <TextInput
      {...p}
      value={p.value?.toString() ?? ""}
      type="number"
      onValueChange={(v) => {
        p.onChange?.(sanitizePort(v));
      }}
    />
  );
}

function sanitizePort(port?: string): number | undefined {
  if (port === undefined) return undefined;
  const val = Number(port);

  if (val < 0) return 0;
  if (val > 65535) return 65535;
  return val;
}
