import React from 'react'

class Checkbox extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      checked: props.default
    }
  }

  handleChange(e) {
    this.setState({
      checked: e.target.checked
    })
    this.props.onChange(this.props.name, e.target.checked)
  }

  render() {
    var id = "checkbox-" + this.props.name
    return (
      <div className="checkbox">
        <label>
          <input
            type="checkbox"
            id={id}
            checked={this.state.checked}
            onChange={this.handleChange.bind(this)}></input>
          {' '}
          {this.props.title}
        </label>
      </div>
    )
  }
}

class CollectionsBox extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      selected: props.selected,
    }
  }

  componentWillReceiveProps(props) {
    this.setState({
      selected: props.selected,
    })
  }

  handleChange(name, checked) {
    var all = this.props.collections.map((c) => c.name)
    var selected = this.state.selected.splice(0)
    if (checked) {
      selected.push(name)
    } else {
      selected = selected.filter((c) => c != name)
    }

    this.setState({selected})
    this.props.onChange(selected)
  }

  render() {
    var result = null
    if (this.props.collections) {
      if (this.props.collections.length) {
        result = this.props.collections.map((col) =>
          <Checkbox
            name={col.name}
            title={col.title}
            key={col.name}
            default={true}
            onChange={this.handleChange.bind(this)}/>
        )
      } else {
        result = <em>none available</em>
      }
    } else {
      result = <em>loading collections ...</em>
    }

    return <div id="collections-box" className="col-sm-2">{result}</div>
  }
}

export default CollectionsBox

@@ -119,23 +119,16 @@
 tate = %7B
-%0A      
 checked:
@@ -138,129 +138,65 @@
 ops.
-default%0A    %7D%0A  %7D%0A%0A  handleChange(e) %7B%0A    this.setState(%7B%0A      checked: e.target.checked%0A    %7D)%0A    this.props.
+checked%7D%0A  %7D%0A%0A  render() %7B%0A    let %7Bname, title, 
 onChange
 (thi
@@ -191,17 +191,20 @@
 onChange
-(
+%7D = 
 this.pro
@@ -209,50 +209,39 @@
 rops
-.name, e.target.checked)%0A  %7D%0A%0A  render() %7B
+%0A    let %7Bchecked%7D = this.state
 %0A   
@@ -264,27 +264,16 @@
 box-%22 + 
-this.props.
 name%0A   
@@ -417,27 +417,16 @@
 hecked=%7B
-this.state.
 checked%7D
@@ -452,36 +452,134 @@
 ge=%7B
-this.handleChange.bind(this)
+(e) =%3E %7B%0A              this.setState(%7Bchecked: e.target.checked%7D)%0A              onChange(name, e.target.checked)%0A            %7D
 %7D%3E%3C/
@@ -612,27 +612,16 @@
        %7B
-this.props.
 title%7D%0A 
@@ -1516,23 +1516,23 @@
         
-default
+checked
 =%7Btrue%7D%0A

simplify Checkbox component