import React from 'react';

export default class Search extends React.Component {

    static get propTypes() {
        return {
            onChange: React.PropTypes.func,
            onEnterPress: React.PropTypes.func,
            placeholder: React.PropTypes.string,
            value: React.PropTypes.string,
            showClear: React.PropTypes.bool
        };
    }

    constructor(props) {
        super();
        this.state = {
            searchValue: props.value || ''
        };
    }

    _handleOnChange = (e) => {
        let searchValue = e.target.value;
        this.setState({
            searchValue: searchValue
        });
        if (this.props.onChange) {
            this.props.onChange(searchValue);
        }
    };

    _handleKeyPress = (e) => {
        let searchValue = e.target.value;
        if (e.key === 'Enter') {
            if (this.props.onEnterPress) {
                this.props.onEnterPress(searchValue);
            }
        }
    };

    getValue = () => {
        return this.state.searchValue;
    };

    handleClear = () => {
        this.setState({
            searchValue: ''
        });
        if (this.props.onEnterPress) {
            this.props.onEnterPress('');
        }
        if (this.props.onChange) {
            this.props.onChange('');
        }
    };

    componentWillReceiveProps(nextProps){

        if(nextProps.value !== this.props.value){
            this.setState({searchValue: nextProps.value});
        }
    }

    render() {
        return (
            <div className={`search-box flex centre-aligned ${this.props.className ? this.props.className : ''}`} style={this.props.style}>
                <input type="text"
                       className="search-content"
                       spellCheck='false'
                       onKeyPress={this._handleKeyPress}
                       onChange={this._handleOnChange}
                       placeholder={this.props.placeholder}
                       value={this.state.searchValue}
                       autoFocus={this.props.autoFocus}
                       style={this.props.inputStyle}
                />
                {
                    this.props.showClear && this.state.searchValue && this.state.searchValue.length > 0 ?
                    (<i onClick={this.handleClear}
                                className={`material-icons search-icon close close-show`}>&#xE5CD;</i>) : 
                    (<i className="material-icons search-icon">&#xe8b6;</i>)
                }
            </div>

        );
    }
}
