React = require 'react'
createClass = require 'create-react-class'
PropTypes = require 'prop-types'

{input, label, span} = require 'react-dom-factories'

RadioInput = createClass

  displayName: 'RadioInput'

  propTypes:
    name: PropTypes.string
    value: PropTypes.string
    className: PropTypes.string
    wrapperLabel: PropTypes.string
    disabled: PropTypes.bool
    onChange: PropTypes.func
    tabIndex: PropTypes.number
    title: PropTypes.string
    id: PropTypes.oneOfType [
      PropTypes.string
      PropTypes.number
    ]

  getDefaultProps: ->
    className: 'radio-input'
    disabled: false
    wrapperLabel: null
    name: null

  render: ->
    {className, onChange, wrapperLabel, checked, disabled, id, name, tabIndex, title, value} = @props

    inputProps = 
      key: 'input'
      ref: 'input'
      name: name
      value: value
      type: 'radio'
      onChange: @handleChange
      checked: checked
      disabled: disabled

    inputProps.tabIndex = tabIndex if tabIndex?
    inputProps.id = id if id?
    inputProps.className = className if className?

    if wrapperLabel?
      label {
        className: "radio-input-label#{if disabled then ' disabled' else ''}"
        htmlFor: id
        title
      }, [
        input(inputProps)
        span {
          key: 'label'
        }, wrapperLabel
      ]
    else
      inputProps.title = title
      input(inputProps)

  getValue: ->
    return @refs.input.value

  handleChange: (e) ->
    {onChange, jsonPath} = @props
    onChange?(e.target.value, jsonPath)

  isChecked: ->
    return @refs.input.checked


module.exports = RadioInput