import React from 'react';
import './ConfigurationItem.css';

export default props => {
  const handleChanged = (e) => {
    const target = e.target;
    if (target.type === 'checkbox') {
      target.value = e.target.checked ? "true" : "false";
    }
    props.changed(target);
  };
  
  let data;
  switch (props.template.type) {
    case "bool":
      data = <input checked={JSON.parse(props.value)}
                    onChange={e=>handleChanged(e)}
                    type={'checkbox'}/>;
    break;

    case "double":
      data = <input min={0.0}
                    onChange={e=>handleChanged(e)}
                    step={"0.01"}
                    className={'ConfigurationItemInput'}
                    type={'number'}
                    value={parseFloat(props.value).toFixed(2)}/>;
    break;

    case "list":
      const options = props.items.map((s, i) => {
        return (
          <option className={'ConfigurationItemOption'} key={i} value={s}>{s}</option>
        );
      });

      data = (
        <select onChange={e=>handleChanged(e)}
                className={'ConfigurationItemSelect'}
                value={props.value}>
          {options}
        </select>
      );
    break;

    case "string":
      data = <input onChange={e=>handleChanged(e)}
                    className={'ConfigurationItemInput'}
                    type={'text'}
                    value={props.value}/>;
    break;

    case "uint8":
      data = <input max={255}
                    min={0}
                    onChange={e=>handleChanged(e)}
                    className={'ConfigurationItemInput'}
                    type={'number'}
                    value={props.value}/>;
    break;

    case "uint16":
      data = <input max={65535}
                    min={0}
                    onChange={e=>handleChanged(e)}
                    className={'ConfigurationItemInput'}
                    type={'number'}
                    value={props.value}/>;
    break;

    case "uint32":
      data = <input max={4294967295}
                    min={0}
                    onChange={e=>handleChanged(e)}
                    className={'ConfigurationItemInput'}
                    type={'number'}
                    value={props.value}/>;
    break;

    case "uint64":
      data = <input max={18446744073709551615}
                    min={0}
                    onChange={e=>handleChanged(e)}
                    className={'ConfigurationItemInput'}
                    type={'number'}
                    value={props.value}/>;
    break;

    default:
      data = <div>{props.value}</div>;
  }

  return (
    <div className={'ConfigurationItem'}>
      <table cellPadding='2'
             width='100%'>
        <tbody>
          <tr>
            <td width='100%'>{props.label}</td>
            <td>{data}</td>
          </tr>
        </tbody>
      </table>
    </div>
  );
};