'use strict';

exports.__esModule = true;

var _isNil2 = require('lodash/isNil');

var _isNil3 = _interopRequireDefault(_isNil2);

var _isUndefined2 = require('lodash/isUndefined');

var _isUndefined3 = _interopRequireDefault(_isUndefined2);

var _isInteger2 = require('lodash/isInteger');

var _isInteger3 = _interopRequireDefault(_isInteger2);

var _isNumber2 = require('lodash/isNumber');

var _isNumber3 = _interopRequireDefault(_isNumber2);

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _react = require('react');

var React = _interopRequireWildcard(_react);

var _classnames = require('classnames');

var _classnames2 = _interopRequireDefault(_classnames);

var _InputGroup = require('./InputGroup');

var _InputGroup2 = _interopRequireDefault(_InputGroup);

var _Input = require('./Input');

var _Input2 = _interopRequireDefault(_Input);

var _Button = require('./Button');

var _Button2 = _interopRequireDefault(_Button);

var _Icon = require('./Icon');

var _Icon2 = _interopRequireDefault(_Icon);

var _utils = require('./utils');

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

var _propTypes2 = _interopRequireDefault(_propTypes);

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }

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

function _defaults(obj, defaults) { var keys = Object.getOwnPropertyNames(defaults); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var value = Object.getOwnPropertyDescriptor(defaults, key); if (value && value.configurable && obj[key] === undefined) { Object.defineProperty(obj, key, value); } } return obj; }

function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }

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) : _defaults(subClass, superClass); }

function getDecimalLength(value) {
  if ((0, _isNumber3.default)(value) && !(0, _isInteger3.default)(value)) {
    return value.toString().split('.')[1].length;
  }
  return 0;
}

function decimals() {
  for (var _len = arguments.length, values = Array(_len), _key = 0; _key < _len; _key++) {
    values[_key] = arguments[_key];
  }

  var lengths = values.map(getDecimalLength);
  return Math.max.apply(Math, lengths);
}

var InputNumber = function (_React$Component) {
  _inherits(InputNumber, _React$Component);

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

    var _this = _possibleConstructorReturn(this, _React$Component.call(this, props));

    _this.handleOnChange = function (value, event) {
      if (!/^-?(?:\d+)?(\.)?(\d+)*$/.test(value) && value !== '') {
        return;
      }
      var isUnControl = (0, _isUndefined3.default)(_this.props.value);

      _this.handleValue(value, event, isUnControl);
    };

    _this.handleBlur = function (event) {
      var _this$props = _this.props,
          max = _this$props.max,
          min = _this$props.min;

      var targetValue = Number.parseFloat(event.target.value);

      if (!Number.isNaN(targetValue)) {
        if (!_this.eqMax(targetValue).inMax) {
          targetValue = max;
        }
        if (!_this.eqMin(targetValue).inMin) {
          targetValue = min;
        }
      } else {
        targetValue = '';
      }
      _this.handleValue(targetValue, event);
    };

    _this.handleWheel = function (event) {
      var _this$props2 = _this.props,
          onWheel = _this$props2.onWheel,
          disabled = _this$props2.disabled;

      if (!disabled && event.target === document.activeElement) {
        event.preventDefault();
        var delta = event.wheelDelta || -event.deltaY || -event.detail;

        if (delta > 0) {
          _this.handleMinus(event);
        }
        if (delta < 0) {
          _this.handlePlus(event);
        }
      }

      onWheel && onWheel(event);
    };

    _this.handlePlus = function (event) {
      var _this$props3 = _this.props,
          step = _this$props3.step,
          max = _this$props3.max;

      var value = +(_this.getValue() || 0);
      var bit = decimals(value, step);
      var nextValue = (value + step).toFixed(bit);
      var output = _this.eqMax(nextValue).inMax ? nextValue : max;

      _this.handleValue(output, event);
    };

    _this.handleMinus = function (event) {
      var _this$props4 = _this.props,
          step = _this$props4.step,
          min = _this$props4.min;

      var value = +(_this.getValue() || 0);
      var bit = decimals(value, step);

      var nextValue = (value - step).toFixed(bit);
      var output = _this.eqMin(nextValue).inMin ? nextValue : min;

      _this.handleValue(output, event);
    };

    _this.state = {
      value: props.defaultValue || 0
    };
    return _this;
  }

  InputNumber.prototype.componentWillMount = function componentWillMount() {
    var value = this.getValue();
    this.setButtonStatus(value);
  };

  InputNumber.prototype.componentWillReceiveProps = function componentWillReceiveProps(nextProps) {
    if (nextProps.value !== this.props.value) {
      this.setButtonStatus(nextProps.value);
    }
  };

  InputNumber.prototype.eqMax = function eqMax(value) {
    var max = this.props.max;

    return {
      inMax: +value <= max,
      equalMax: +value >= max
    };
  };

  InputNumber.prototype.eqMin = function eqMin(value) {
    var min = this.props.min;

    return {
      inMin: +value >= min,
      equalMin: +value <= min
    };
  };

  InputNumber.prototype.getValue = function getValue() {
    var value = this.props.value;

    return (0, _isUndefined3.default)(value) ? this.state.value : value;
  };

  InputNumber.prototype.setButtonStatus = function setButtonStatus(value) {
    if (typeof value !== 'undefined') {
      this.setState({
        disabledUpButton: this.eqMax(value).equalMax,
        disabledDownButton: this.eqMin(value).equalMin
      });
    }
  };

  InputNumber.prototype.handleValue = function handleValue(currentValue, event, input) {
    var value = this.state.value;
    var onChange = this.props.onChange;


    this.setButtonStatus(currentValue);

    if (currentValue !== value) {
      this.setState({
        value: currentValue
      });

      if (!input && onChange) {
        onChange(currentValue, event);
      }
    }
  };

  InputNumber.prototype.render = function render() {
    var _props = this.props,
        disabled = _props.disabled,
        size = _props.size,
        prefixElement = _props.prefix,
        postfix = _props.postfix,
        className = _props.className,
        classPrefix = _props.classPrefix,
        step = _props.step,
        rest = _objectWithoutProperties(_props, ['disabled', 'size', 'prefix', 'postfix', 'className', 'classPrefix', 'step']);

    var _state = this.state,
        disabledUpButton = _state.disabledUpButton,
        disabledDownButton = _state.disabledDownButton;


    var value = this.getValue();
    var addPrefix = (0, _utils.prefix)(classPrefix);
    var classes = (0, _classnames2.default)(classPrefix, className);
    var unhandled = (0, _utils.getUnhandledProps)(InputNumber, rest);

    return React.createElement(
      _InputGroup2.default,
      _extends({}, unhandled, { className: classes, disabled: disabled, size: size }),
      prefixElement && React.createElement(
        _InputGroup2.default.Addon,
        null,
        prefixElement
      ),
      React.createElement(_Input2.default, {
        type: 'text',
        step: step,
        onChange: this.handleOnChange,
        onBlur: this.handleBlur,
        value: (0, _isNil3.default)(value) ? '' : value,
        onWheel: this.handleWheel,
        disabled: disabled
      }),
      postfix && React.createElement(
        _InputGroup2.default.Addon,
        null,
        postfix
      ),
      React.createElement(
        'span',
        { className: addPrefix('btn-group-vertical') },
        React.createElement(
          _Button2.default,
          {
            className: addPrefix('touchspin-up'),
            onClick: this.handlePlus,
            disabled: disabledUpButton || disabled
          },
          React.createElement(_Icon2.default, { icon: 'arrow-up-line' })
        ),
        React.createElement(
          _Button2.default,
          {
            className: addPrefix('touchspin-down'),
            onClick: this.handleMinus,
            disabled: disabledDownButton || disabled
          },
          React.createElement(_Icon2.default, { icon: 'arrow-down-line' })
        )
      )
    );
  };

  return InputNumber;
}(React.Component);

InputNumber.defaultProps = {
  min: -Infinity,
  max: Infinity,
  step: 1
};
InputNumber.handledProps = ['className', 'classPrefix', 'defaultValue', 'disabled', 'max', 'min', 'onChange', 'onWheel', 'postfix', 'prefix', 'size', 'step', 'value'];
InputNumber.propTypes = {
  className: _propTypes2.default.string,
  classPrefix: _propTypes2.default.string.isRequired,
  min: _propTypes2.default.number.isRequired,
  max: _propTypes2.default.number.isRequired,
  step: _propTypes2.default.number.isRequired,
  value: _propTypes2.default.oneOfType([_propTypes2.default.number, _propTypes2.default.string]),
  defaultValue: _propTypes2.default.oneOfType([_propTypes2.default.number, _propTypes2.default.string]),
  prefix: _propTypes2.default.node,
  postfix: _propTypes2.default.node,
  disabled: _propTypes2.default.bool,
  size: _propTypes2.default.oneOf(['lg', 'md', 'sm', 'xs']),
  onWheel: _propTypes2.default.func,
  onChange: _propTypes2.default.func
};
exports.default = (0, _utils.defaultProps)({
  classPrefix: 'input-number'
})(InputNumber);