import {
  TextBox,
  MaskedTextBox,
  NumericTextBox,
} from "@progress/kendo-react-inputs";
import { TextBoxProps } from "./TextBoxWidgetView";

const getCommonProps = (props: TextBoxProps) => {
  const {
    widgetStyle,
    name,
    readOnly,
    disabled,
    onChange,
    onKeyDown,
    onKeyUp,
    onBlur,
  } = props;

  return {
    id: widgetStyle?.id || "",
    className: widgetStyle?.className || "",
    style: widgetStyle?.inline || {},
    name,
    readOnly,
    disabled,
    onChange,
    onBlur,
    onKeyDown,
    onKeyUp,
  };
};

const renderTextBoxComponent = (
  Component: any,
  props: TextBoxProps,
  additionalProps: any
) => {
  const commonProps = getCommonProps(props);
  return <Component {...commonProps} {...additionalProps} />;
};

export const renderMaskedTextBox = (props: TextBoxProps) => {
  const { mask, value, defaultValue } = props;
  return renderTextBoxComponent(MaskedTextBox, props, {
    mask,
    value:
      value !== undefined && value !== null ? (value as string) : "",
    defaultValue: defaultValue ? (defaultValue as string) : undefined,
  });
};

export const renderNumericTextBox = (props: TextBoxProps) => {
  const { placeHolder, max, min, value, defaultValue } = props;
  return renderTextBoxComponent(NumericTextBox, props, {
    placeholder: placeHolder,
    max,
    min,
    value:
      value !== undefined && value !== null ? (value as number) : null,
    defaultValue: defaultValue ? (defaultValue as number) : undefined,
  });
};

export const renderTextBox = (props: TextBoxProps) => {
  const { type, placeHolder, max, value, defaultValue } = props;
  return renderTextBoxComponent(TextBox, props, {
    type,
    placeholder: placeHolder,
    maxLength: max,
    value:
      value !== undefined && value !== null ? (value as string) : "",
    defaultValue: defaultValue ? (defaultValue as string) : undefined,
  });
};