'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _templateObject = _taggedTemplateLiteral(['\n  margin: auto;\n  margin-top: 100px;\n  width: 50%;\n  padding: 10px;\n  text-align: center;\n'], ['\n  margin: auto;\n  margin-top: 100px;\n  width: 50%;\n  padding: 10px;\n  text-align: center;\n']);

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

var _propTypes = require('prop-types');

var _propTypes2 = _interopRequireDefault(_propTypes);

var _styledComponents = require('styled-components');

var _styledComponents2 = _interopRequireDefault(_styledComponents);

var _InputBox = require('./InputBox');

var _InputBox2 = _interopRequireDefault(_InputBox);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

function _taggedTemplateLiteral(strings, raw) { return Object.freeze(Object.defineProperties(strings, { raw: { value: Object.freeze(raw) } })); }

var Wrapper = _styledComponents2.default.div(_templateObject);

var ReactIndividualCharacterInputBoxes = function (_Component) {
  _inherits(ReactIndividualCharacterInputBoxes, _Component);

  function ReactIndividualCharacterInputBoxes(props) {
    _classCallCheck(this, ReactIndividualCharacterInputBoxes);

    var _this = _possibleConstructorReturn(this, (ReactIndividualCharacterInputBoxes.__proto__ || Object.getPrototypeOf(ReactIndividualCharacterInputBoxes)).call(this, props));

    _this.state = { characterArray: Array(props.amount).fill(null) };

    _this.handleKeyDown = _this.handleKeyDown.bind(_this);
    _this.handleFocus = _this.handleFocus.bind(_this);
    _this.handleChange = _this.handleChange.bind(_this);
    _this.inputElements = {};
    return _this;
  }

  _createClass(ReactIndividualCharacterInputBoxes, [{
    key: 'componentDidMount',
    value: function componentDidMount() {
      if (this.props.autoFocus) {
        this.inputElements['input0'].select();
      }
    }
  }, {
    key: 'shouldComponentUpdate',
    value: function shouldComponentUpdate(nextProps, nextState) {
      if (this.props.amount !== nextProps.amount || this.props.inputRegExp !== nextProps.inputRegExp) {
        return true;
      }
      return false;
    }
  }, {
    key: 'componentWillReceiveProps',
    value: function componentWillReceiveProps(nextProps) {
      if (this.props.amount !== nextProps.amount) {
        this.setState({ characterArray: Array(nextProps.amount).fill(null) });
        this.props.handleOutputString('');
      }
    }
  }, {
    key: 'renderItems',
    value: function renderItems() {
      var _this2 = this;

      var items = [];

      for (var i = 0; i < this.props.amount; i++) {
        items.push(_react2.default.createElement(_InputBox2.default, {
          type: this.props.password ? 'password' : 'text',
          key: i,
          handleKeyDown: this.handleKeyDown,
          handleFocus: this.handleFocus,
          handleChange: this.handleChange,
          name: 'input' + i,
          inputRef: function inputRef(el) {
            if (!el) return;
            _this2.inputElements[el.name] = el;
          }
        }));
      }

      return items;
    }
  }, {
    key: 'render',
    value: function render() {
      return _react2.default.createElement(
        Wrapper,
        null,
        _react2.default.createElement(
          'div',
          null,
          this.renderItems()
        )
      );
    }
  }, {
    key: 'handleChange',
    value: function handleChange(_ref) {
      var target = _ref.target;

      if (target.value.match(this.props.inputRegExp)) {
        this.focusNextChar(target);
        this.setModuleOutput(target);
      } else {
        target.value = this.state.characterArray[target.name.replace('input', '')];
      }
    }
  }, {
    key: 'handleKeyDown',
    value: function handleKeyDown(_ref2) {
      var target = _ref2.target,
          key = _ref2.key;

      if (key === 'Backspace') {
        if (target.value === '' && target.previousElementSibling !== null) {
          target.previousElementSibling.value = '';
          this.focusPrevChar(target);
        } else {
          target.value = '';
        }
        this.setModuleOutput(target);
      } else if (key === 'ArrowLeft') {
        this.focusPrevChar(target);
      } else if (key === 'ArrowRight') {
        this.focusNextChar(target);
      }
    }
  }, {
    key: 'handleFocus',
    value: function handleFocus(_ref3) {
      var target = _ref3.target;

      var el = target;
      setTimeout(function () {
        el.select();
      }, 0);
    }
  }, {
    key: 'focusPrevChar',
    value: function focusPrevChar(target) {
      if (target.previousElementSibling !== null) {
        target.previousElementSibling.focus();
      }
    }
  }, {
    key: 'focusNextChar',
    value: function focusNextChar(target) {
      if (target.nextElementSibling !== null) {
        target.nextElementSibling.focus();
      }
    }
  }, {
    key: 'setModuleOutput',
    value: function setModuleOutput(target) {
      var _this3 = this;

      this.setState(function (prevState) {
        var updatedCharacters = prevState.characterArray.map(function (character, number) {
          return _this3.inputElements['input' + number].value;
        });
        return { characterArray: updatedCharacters };
      }, function () {
        return _this3.props.handleOutputString(_this3.state.characterArray.join(''));
      });
    }
  }]);

  return ReactIndividualCharacterInputBoxes;
}(_react.Component);

ReactIndividualCharacterInputBoxes.defaultProps = {
  amount: 5,
  autoFocus: false,
  inputRegExp: /^[0-9]$/,
  password: false
};
ReactIndividualCharacterInputBoxes.propTypes = {
  amount: _propTypes2.default.number,
  autoFocus: _propTypes2.default.bool,
  inputRegExp: _propTypes2.default.instanceOf(RegExp),
  password: _propTypes2.default.bool,
  handleOutputString: _propTypes2.default.func.isRequired
};

exports.default = ReactIndividualCharacterInputBoxes;