require('./plaintext-contenteditable.css');

var React = require('react');

/*************************************************
 * PlainTextContentEditable
 * -----------------------------------------------
 *  Acts like a textarea but can be used with a
 *  column-width/count CSS styling
 * -----------------------------------------------
 * Props:
 *  - onChange   : function(event)
 *                 to get ev.target.value
 *  - placeholder: placeholder text
 *  - className  : className to pass the div
 *************************************************/
var PlainTextContentEditable = React.createClass({
  getDefaultProps() {
    return {
      onChange: function() {},
      placeholder: "",
      className: ""
    };
  },
  getInitialState() {
    return {
      text: ""
    };
  },
  getText(el) {
    return el.innerText || this.getTextForFirefox(el);
  },
  getTextForFirefox(el) {
    // Taken from http://stackoverflow.com/a/3908094
    var text = "";
    if (typeof window.getSelection != "undefined") {
      var sel = window.getSelection();
      var tempRange = sel.getRangeAt(0);
      sel.removeAllRanges();
      var range = document.createRange();
      range.selectNodeContents(el);
      sel.addRange(range);
      text = sel.toString();
      sel.removeAllRanges();
      sel.addRange(tempRange);
    }

    return text;
  },
  onTextChange(ev) {
    var text = this.getText(ev.target);
    this.setState({ text: text });
    this.props.onChange({
      target: {
        value: text
      }
    });
  },
  onPaste(ev) {
    ev.preventDefault();
    var text = ev.clipboardData.getData("text");
    document.execCommand('insertText', false, text);
  },
  getClassName() {
    var placeholder = this.state.text === "" ? "comPlainTextContentEditable--has-placeholder" : "";
    return `comPlainTextContentEditable ${placeholder} ${this.props.className}`;
  },
  render() {
    return (
      <div
        ref="content"
        contentEditable="true"
        className={ this.getClassName() }
        onPaste={ this.onPaste }
        onInput={ this.onTextChange }
        placeholder={ this.props.placeholder }
      />
    );
  }
});

module.exports = PlainTextContentEditable;