context = window
rest = window.JK.Rest()
logger = context.JK.logger

@CheckBoxList = React.createClass({
  objects: []

  inited: false

  componentDidMount: () ->
    @root = $(@getDOMNode())
    @wireICheck()

  componentDidUpdate: () ->
    @wireICheck()

  wireICheck: () ->
    checkBoxes = @root.find('input[type="checkbox"]')
    if checkBoxes.length > 0
      if @inited
        # it's expensive to run context.JK.checkbox
        return
      @inited = true
      context.JK.checkbox(checkBoxes, true)
      checkBoxes.on('ifChanged', (e) => @checkIfCanFire(e))

  checkIfCanFire: (e) ->
    if @iCheckIgnore
      return

    @onItemChanged()

  onItemChanged: (e) ->
    # e.preventDefault()

    selectedObjects = @selectedObjects()
    @setState({selectedObjects: selectedObjects})
    this.props.onItemChanged(this.props.objectName, selectedObjects)

  selectedObjects: ->
    selected=[]
    @root = jQuery(this.getDOMNode())
    $(".checkItem input[type=checkbox]:checked", @root).each ->
      selected.push $(this).data("object-id")
    selected

  render: () ->
    object_options = []

    for object in this.props.sourceObjects
      nm = "check_#{object.id}"
      checked = @isChecked(object.id)
      object_options.push `<div key={object.id} className='checkItem'><input type='checkbox' key={object.id} name={nm} data-object-id={object.id}  checked={checked}></input><label htmlFor={nm}>{object.description}</label><br className="clearall"/></div>`

    `<div className="CheckBoxList react-component">
        <div className="checkbox-scroller left">
          {object_options}
        </div>
    </div>`

  isChecked: (id) ->
    this.state.selectedObjects? && id in this.state.selectedObjects


  getInitialState: () ->
    {selectedObjects:@props.selectedObjects}

  componentWillReceiveProps: (nextProps) ->
    @setState({selectedObjects: nextProps.selectedObjects})

})