import React from 'react';
import {Menu, MenuItem} from 'material-ui/Menu';
import Popover from 'material-ui/Popover/Popover';
import {cloneDeep, checkDeepEquals} from '../../UtilitiesFunctions/objectUtilities';
import * as _ from "lodash";

const anchorOrigin = {
    horizontal: 'left',
    vertical: 'bottom',
};
const targetOrigin = {
    horizontal: 'left',
    vertical: 'top',
};
const style = {
    float: 'left',
    padding: '0px 10px 5px 10px'
};

export default class SelectField extends React.Component {

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

    constructor(props) {
        super(props);
        let selectedValues = [], selectedObjects = [];
        if(props.defaultSelectedValues && props.defaultSelectedValues.length > 0){
            props.defaultSelectedValues.forEach(function(item){
                selectedValues.push(item.value);
            });
            selectedObjects = props.defaultSelectedValues;
        }

        this.state = {
            open: false,
            selectedValues: selectedValues,
            selectedObjects: selectedObjects,
            completeData: cloneDeep(props.items),
            items: cloneDeep(props.items),
            searchString: '',
            showLoader: false,
            scrollTop: 0
        };
    }

    componentDidUpdate(){
        if(this.state.scrollTop !==0){
            let elem = document.querySelectorAll("div[role='presentation']");
            elem[0].scrollTop = this.state.scrollTop;
            let _self = this;
            setTimeout(() => {
                _self.setState({scrollTop: 0});
            }, 200);
        }
    }

    componentWillReceiveProps(nextProps) {
        if(!checkDeepEquals(this.state.completeData, nextProps.items) && nextProps.items && nextProps.items.length > 0){
            this.setState({
                completeData: cloneDeep(nextProps.items),
                items: cloneDeep(nextProps.items)
            });
        }

    }

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

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

    handleOnClick = (event) => {
        if(this && this.props && !this.props.disabled){
        let items = this.state.items;
        this.state.selectedObjects.forEach((object) => {
            let index = _.findIndex(items, function (item) {
                return item.value === object.value;
            });
            if(index !== -1){
                items.splice(index, 1);
                items = [object, ...items];
            }
        });        
        this.setState({
            open: true,
            anchorEl: event.currentTarget,
            items: items
        });
    }
    }

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

        if(_indexOfArray>=0){
            _selectedValues.splice(_indexOfArray, 1);

        }else{
            if(!Array.isArray(_selectedValues)){
                _selectedValues = [];
            }
            _selectedValues.push(menuItem.value);
        }

        if(_indexOfObject>=0){
            _selectedObjects.splice(_indexOfObject, 1);
        }
        else{
            if(!Array.isArray(_selectedObjects)){
                _selectedObjects = [];
            }
            _selectedObjects.push(menuItem);
        }
        let elem = document.querySelectorAll("div[role='presentation']");
        this.setState({
            selectedValues: _selectedValues,
            selectedObjects: _selectedObjects,
            scrollTop: (elem[0] && elem[0].scrollTop)?elem[0].scrollTop:0
        });
        if(this.props.onFilterChange) {
            this.props.onFilterChange(_selectedObjects);
        }
        if(this.props.onValueChange)
            this.props.onValueChange(_selectedObjects);
    };

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

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

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

    handleOnSearchChange = (event) => {
        let searchString = event.target.value;
        if(!this.props.multiLable) {
            let itemFilterData = [];
            let completeData = cloneDeep(this.state.completeData);
            completeData.forEach((itemData) => {
                if (itemData.label.toLowerCase().indexOf(searchString.toLowerCase()) >= 0)
                    itemFilterData.push(itemData);
            });
            this.setState({items: itemFilterData, searchString: searchString});
        }
        this.setState({showLoader: false, searchString: searchString});
        setTimeout(() => {
            this.searchInput.focus();
        }, 10);
    }

    getPopOver = () => {
        let keySet = Object.keys(this.state.items);
        let _self = this;
        return(
            <Popover
                open={this.state.open}
                anchorEl={this.state.anchorEl}
                anchorOrigin={anchorOrigin}
                targetOrigin={targetOrigin}
                onRequestClose={this.handleRequestClose}
                className="popover edit-alert-filter"
            >
                <div className="search-box-container">
                    <input
                        type="text"
                        placeholder="Search Here"
                        onChange={this.handleOnSearchChange}
                        className="select-search"
                        value={this.state.searchString}
                        key="search-input"
                        ref={(input) => { this.searchInput = input; }}
                    />
                </div>

                {/*{*/}
                    {/*( this.props.multiLabel)?*/}
                        {/*<div>*/}
                        {/*{*/}
                            {/*keySet.map((listLabel) => {*/}
                            {/*return (*/}
                                {/*<Menu>*/}
                                    {/*<p className="menu-title">{listLabel}</p>*/}
                                    {/*{*/}
                                        {/*this.state.items[listLabel].map((listData, i) => {*/}
                                            {/*return (*/}
                                                {/*<MenuItem key={i}*/}
                                                          {/*className={'dropdown-menu ' + (this.isSelected(listData.label) ? 'selected' : '')}*/}
                                                          {/*primaryText={listData.label}*/}
                                                          {/*onTouchTap={this.onMenuItemClick.bind(this, listData, _self.props.items[listLabel])}*/}
                                                          {/*style={style}*/}
                                                          {/*innerDivStyle={{width: '111px'}}*/}
                                                          {/*leftIcon={*/}
                                                              {/*(this.isSelected(listData.label) ?*/}
                                                                  {/*<i className='material-icons checkbox selected'>check_box</i> :*/}
                                                                  {/*<i className='material-icons checkbox'>check_box_outline_blank</i>)}*/}
                                                {/*/>);*/}
                                        {/*})*/}
                                    {/*}*/}
                                {/*</Menu>*/}
                            {/*)*/}
                        {/*})*/}
                    {/*}*/}
                        {/*</div>*/}
                    {/*:''*/}
                {/*}*/}
                {
                    (this.state.items &&  !this.props.multiLabel) ?
                        <Menu>
                            {
                                this.state.items.map((item, i) => {
                                    return (
                                        <MenuItem key={i}
                                                  className={'dropdown-menu ' + (this.isSelected(item.value) ? 'selected' : '')}
                                                  primaryText={item.label}
                                                  onTouchTap={this.onMenuItemClick.bind(this, item, this.state.items)}
                                                  style={style}
                                                  leftIcon={
                                                      (this.isSelected(item.value) ?
                                                          <i className='material-icons checkbox selected'>check_box</i> :
                                                          <i className='material-icons checkbox'>check_box_outline_blank</i>)}
                                        />);
                                })
                            }
                        </Menu>
                        : ''
                }
                {
                    (this.state.items.length === 0 && !this.state.showLoader)?
                        <p className="no-result">No Result Available</p>
                    :''
                }
            </Popover>
        )
    }

    render() {
        if(this.props.separateLabel){
            return (
                <div className={`custom-select-wrapper`} onClick={this.handleOnClick}>
                    <span className="label overflow-wrap">{this.props.label}</span>
                    <div className={`custom-select-box pointer noselect ${this.props.disabled ? 'disable-background-select' : ''}`} onTouchTap={this.handleTouchTap}>
                        {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.props.disabled? '' : this.getPopOver()}
                    </div>
                </div>
            );
        }
        else{
            return(
                <div className="custom-select-box pointer noselect" onTouchTap={this.handleTouchTap}>
                    <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.props.disabled? '' : this.getPopOver()}
                </div>
            )
        }
    }
}
