import React, { PropTypes } from 'react';
import ReactDOM from 'react-dom';
import classNames from 'classnames';
import { ENTER, ESCAPE } from '../../constants';

const defaultProps = {
  isChickletNone: false,
  hasInitialValues: false,
  onSelectionClearSelectedValueFromTextbox: true,
}

const propTypes = {
  setSelectedItems: PropTypes.func,
  isChickletNone: PropTypes.bool,
  hasInitialValues: PropTypes.bool,
  lastInitialValue: PropTypes.object,
  placeholderTextLabel: PropTypes.string,
  setKdSelectEntityLoading: PropTypes.func,
  handleRemove: PropTypes.func,
}

class kdSelectString extends React.Component {

  constructor(props) {
    super(props);

    this.handleKeyDown = this.handleKeyDown.bind(this);
    this.renderInput = this.renderInput.bind(this);
    this.addItem = this.addItem.bind(this);
  }

  initialInputValue(){
    if (this.props.isChickletNone && this.props.hasInitialValues) {
      return this.props.lastInitialValue.label;
    }
  }

  setInputValue(value){
    if (this.kdSelectString != null ) {
      this.kdSelectString.value = value || "";
    }
  }

  addItem(value) {
    this.props.addItem(value);
    if (this.props.isChickletNone) {
      this.setInputValue(value);
    } else {
      this.props.onSelectionClearSelectedValueFromTextbox && this.setInputValue();
    }
  }

  handleKeyDown({ keyCode, target }){
    switch (keyCode){
      case ENTER:
        this.addItem(target.value);
        break;
      case ESCAPE:
        this.setInputValue();
        break;
      default:
        break;
    }
  }


  renderInput() {
    let inputClass = classNames('o-kd-select-string',
            {'u-input-chicklet-none': this.props.isChickletNone });
    return (
      <input className={inputClass}
             type="text"
             ref={ref => this.kdSelectString = ref}
             placeholder={this.props.placeholderTextLabel}
             onKeyDown={this.handleKeyDown}
             defaultValue={this.initialInputValue()}
      />);
  }

  render() {
    return (
      <div ref={ref => this.rootElement = ref} className="c-kd-select-string">
        {this.renderInput()}
      </div>
    );
  }
};

kdSelectString.defaultProps = defaultProps;

kdSelectString.propTypes = propTypes;

export default kdSelectString;