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

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


CheckboxInput = createClass

  displayName: 'CheckboxInput'

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

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

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

    inputProps = 
      key: 'input'
      ref: 'input'
      name: name
      type: 'checkbox'
      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: 'checkbox-input-label'
        htmlFor: id
      }, [
        input(inputProps)
        span {
          key: 'label'
        }, wrapperLabel
      ]
    else
      input(inputProps)

  getValue: ->
    return @refs.input.checked

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


module.exports = CheckboxInput