import React from 'react';
import {Menu, MenuItem} from 'material-ui/Menu';
import Popover from 'material-ui/Popover/Popover';
import Checkbox from 'material-ui/Checkbox';
import FontIcon from 'material-ui/FontIcon';

const anchorOrigin = {
  horizontal: 'left',
  vertical: 'bottom',
},
targetOrigin = {
  horizontal: 'left',
  vertical: 'top',
};

export default class CustomSelectFilter extends React.Component {

    static get propTypes() {
      return {
        multiple: React.PropTypes.bool,
        onFilterChange: React.PropTypes.func,
        displaySelected: React.PropTypes.func
      };
    }

    constructor(props) {
      super(props);
      let selectedValues = [], selectedObjects = [];
      if(props.multiple && props.defaultSelectedValues && props.defaultSelectedValues.length){
        props.defaultSelectedValues.forEach(function(item){
          selectedValues.push(item.label);
        });
        selectedObjects = props.defaultSelectedValues;
      }
      else{
        if(props.defaultSelectedIndex || props.defaultSelectedIndex === 0) {
          selectedValues.push(props.items[props.defaultSelectedIndex].label);
          selectedObjects.push(props.items[props.defaultSelectedIndex]);
        }
      }
      this.state = {
         open: false,
         selectedValues: selectedValues,
         selectedObjects: selectedObjects
       };
    }

    componentWillReceiveProps(nextProps) {
      if(nextProps.items.length !== this.props.items.length) {
        let selectedValues = [], selectedObjects = [];
        if(nextProps.defaultSelectedIndex || nextProps.defaultSelectedIndex === 0) {
          selectedValues.push(nextProps.items[nextProps.defaultSelectedIndex].label);
          selectedObjects.push(nextProps.items[nextProps.defaultSelectedIndex]);
        }
        this.setState({
          selectedValues: selectedValues,
          selectedObjects: selectedObjects
        });
      }
      if(nextProps.defaultSelectedValues){
        this.setState({defaultSelectedValues:nextProps.defaultSelectedValues});
      }
    }

    handleTouchTap = (event) => {
      // This prevents ghost click.
      event.preventDefault();
      this.setState({
        open: true,
        anchorEl: event.currentTarget,
      });
    };

    handleRequestClose = () => {
      this.setState({
        open: false
      });
    };

    onMenuItemClick = (event, menuItem, index) => {
      event.preventDefault();
      let _itemList = this.props.items;
      let _selectedValues = this.state.selectedValues;
      let _selectedObjects = this.state.selectedObjects;
      let _indexOfArray = _selectedValues.indexOf(_itemList[index].label);
      let _indexOfObject = -1;
      for(let i=0, len=_selectedObjects.length; i<len;i++){
        if(_selectedObjects[i].id === _itemList[index].id){
          _indexOfObject = i;
          break;
        }
      }

      if(_indexOfArray>=0){
        _selectedValues.splice(_indexOfArray, 1);
        
      }else{
        if(!this.props.multiple){
          _selectedValues = [];
          _selectedValues.push(_itemList[index].label);
        }
        else{
          if(!Array.isArray(_selectedValues)){
            _selectedValues = [];   
          }
          _selectedValues.push(_itemList[index].label);
        }    
      }

      if(_indexOfObject>=0){
        _selectedObjects.splice(_indexOfObject, 1);
      }
      else{
        if(!this.props.multiple){
          _selectedObjects = [];
          _selectedObjects.push(_itemList[index]);        
        }
        else{
          if(!Array.isArray(_selectedObjects)){
            _selectedObjects = [];   
          }
          _selectedObjects.push(_itemList[index]);        
        }        
      }

      this.setState({
        selectedValues: _selectedValues,
        selectedObjects: _selectedObjects
      });
      if(this.props.onFilterChange) {
        this.props.onFilterChange(_selectedObjects);
      }
      if(!this.props.multiple){
        this.handleRequestClose();
      }

    };

    isSelected = (label) => {
      return (this.state.selectedValues.indexOf(label)>=0) ? true: false;
    }

    valueAsString = () => {
      return this.state.selectedValues.join(', ');
    }

    value = () => {
      return this.state.selectedValues;
    }

    getPopOver = () => {
      return(
        <Popover
          open={this.state.open}
          anchorEl={this.state.anchorEl}
          anchorOrigin={anchorOrigin}
          targetOrigin={targetOrigin}
          onRequestClose={this.handleRequestClose}>
          <Menu onItemTouchTap={this.onMenuItemClick}>
            {
              this.props.items.map((item,i) => {
                return (<MenuItem key={i} className={'dropdown-menu '+(this.isSelected(item.label) ? 'selected' : '')}
                          primaryText={item.label}
                          leftIcon={
                              (this.isSelected(item.label) ?
                                  <i className='material-icons checkbox selected'>check_box</i>:
                                  <i className='material-icons checkbox'>check_box_outline_blank</i>)}
                          />);
              })
            }
          </Menu>
        </Popover>
      )
    }

    render() {
      if(this.props.separateLabel){
        return (
          <div className="flex inline centre-aligned custom-select-wrapper">
            <span className="label overflow-wrap">{this.props.label}</span>
            <div className="custom-select-box pointer noselect flex">
              {this.props.showSelected === false?(null):(<span className="selected-value">{this.props.displaySelected? this.props.displaySelected(this.state.selectedObjects) : this.state.selectedValues}</span>)}
              {this.props.showArrow === false?(null):(<i className="material-icons icon">{this.state.open?'keyboard_arrow_up':'keyboard_arrow_down'}</i>)}
              {this.getPopOver()}    
            </div>
          </div>
        );
      }
      else{
        return(
          <div className="custom-select-box flex inline centre-aligned pointer noselect">
            <span className="label">{this.props.label}</span>
            {this.props.showSelected === false?(null):(<span className="selected-value">{this.props.displaySelected? this.props.displaySelected(this.state.selectedValues) : this.state.selectedValues}</span>)}
            {this.props.showArrow === false?(null):(<i className="material-icons icon">{this.state.open?'keyboard_arrow_up':'keyboard_arrow_down'}</i>)}
            {this.getPopOver()}
          </div>
        )
      }        
    }
}
