import React from 'react';
import {Menu, MenuItem} from 'material-ui/Menu';
import Search from './Search';

export default class SelectWithSearch extends React.Component {

  static get propTypes() {
    return {
      dataSource: React.PropTypes.array.isRequired,
      menuStyle: React.PropTypes.object,
      onItemSelect: React.PropTypes.func
    };
  }

  constructor(props, context) {
    super();
    this.state = {
      dataSource: props.dataSource || []
    };
  }

  componentWillReceiveProps = (nextProps) => {
    if(nextProps.dataSource) {
      this.setState({
        dataSource: nextProps.dataSource
      });
    }
  }

  selectValue = (obj) => {
    if(this.props.onItemSelect) {
      this.props.onItemSelect(obj);
    }
  };

  filterData = (searchVal) => {
    if(this.props.dataSource && this.props.dataSource.length > 0) {
      this.setState({
        dataSource: this.props.dataSource.filter((obj) => (obj.label.toLowerCase().indexOf(searchVal.toLowerCase()) !== -1))
      });
    }
  };

  render() {
    let menuItems = this.state.dataSource.map((obj, i) => {
      return (<MenuItem
                key={obj.label + i}
                className="menu-item"
                primaryText={obj.label}
                onClick={this.selectValue.bind(this, obj)}
              />);
    });
    const menuStyle = Object.assign({
      overflow: 'auto'
    }, this.props.menuStyle);
    return (<div>
        <div className="search-locations">
          <Search placeholder="Search..." onChange={this.filterData} autoFocus={true}/>
        </div>
        <Menu className="menu" style={menuStyle} disableAutoFocus={true}>
          {menuItems}
        </Menu>
      </div>
    );
  }
}
