import React from 'react';
import '../base';

import styles from './MultiSelectGroup.styl';

export default class MultiSelectGroup extends React.Component {
  constructor(props) {
    super(props);
    this.handleOnChange = this.handleOnChange.bind(this);
  }

  handleOnChange(event, value) {
    const newSelected = [].concat(this.props.selected);
    const index = newSelected.indexOf(value);
    if (event.target.checked) {
      if (index < 0) newSelected.push(value);
    } else if (index > -1) newSelected.splice(index, 1);

    const possibleValues = React.Children.map(this.props.children, (c) => c.props.value);

    // remove not own values
    let cleanedSelected = newSelected;
    if (this.props.exclusive) {
      cleanedSelected = newSelected.filter((selected) => possibleValues.indexOf(selected) > -1);
    }

    if (this.props.onChange) this.props.onChange(cleanedSelected);
  }

  render() {
    const { children, selected } = this.props;

    return (
      <div className={styles.group}>
        {
          React.Children.map(children, (child) => {
            const addProps = {
              onChange: (e) => { this.handleOnChange(e, child.props.value); },
              checked: selected.includes(child.props.value),
              readOnly: true
            };

            return React.cloneElement(child, addProps);
          })
        }
      </div>
    );
  }
}
