'use strict';

/** @jsx createElement */
import { createElement, Component } from 'rax';

import { getText, genEventObject } from './util';

export default class InputComponent extends Component {
  constructor(props) {
    super(props);

    this.changeHandler = this.changeHandler.bind(this);
    this.focusHandler = this.focusHandler.bind(this);
    this.blurHandler = this.blurHandler.bind(this);
    this.focus = this.focus.bind(this);
    this.blur = this.blur.bind(this);
  }

  changeHandler(e) {
    const value = getText(e);

    const { maxLength } = this.props;

    if (maxLength && value && value.length > maxLength) return;
    if ('value' in this.props) {
      this.setState({ value });
    }
    this.trigger('onChange', value, genEventObject(e));
  }

  trigger(fn, ...attrs) {
    if (typeof fn === 'string') fn = this.props[fn];
    if (!(typeof fn === 'function')) return;

    return fn.apply(this, attrs);
  }
  calcBorder(style) {
    ['Color', 'Style', 'Width'].map((attr) => {
      if (style[`border${attr}`]) {
        const attrObj = {
          [`borderTop${attr}`]: style[`border${attr}`],
          [`borderLeft${attr}`]: style[`border${attr}`],
          [`borderRight${attr}`]: style[`border${attr}`],
          [`borderBottom${attr}`]: style[`border${attr}`],
        };
        delete style[`border${attr}`];
        style = Object.assign({}, attrObj, style);
      }
    });
    return style;
  }
  focusHandler(e) {
    this.trigger('onFocus', e);
  }
  focus() {
    this.focusInput();
  }
  focusInput() {
    this.refs.input.focus && this.refs.input.focus();
  }
  blur() {
    this.blurInput();
  }
  blurInput() {
    this.refs.input.blur && this.refs.input.blur();
  }
  blurHandler(e) {
    this.setState({
      focus: false,
    });

    this.trigger('onBlur', e);
  }
}
