'use strict';

exports.__esModule = true;

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 _propTypes = require('prop-types');

var _propTypes2 = _interopRequireDefault(_propTypes);

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

var _Input2 = _interopRequireDefault(_Input);

var _ErrorMessage = require('./ErrorMessage');

var _ErrorMessage2 = _interopRequireDefault(_ErrorMessage);

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

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

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 _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); }

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

  function FormControl(props, context) {
    _classCallCheck(this, FormControl);

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

    _initialiseProps.call(_this);

    if (!context.form) {
      throw new Error('FormControl must be inside a component decorated with <Form>');
    }

    var _context$form = context.form,
        _context$form$formVal = _context$form.formValue,
        formValue = _context$form$formVal === undefined ? {} : _context$form$formVal,
        _context$form$formDef = _context$form.formDefaultValue,
        formDefaultValue = _context$form$formDef === undefined ? {} : _context$form$formDef;

    var name = props.name;

    _this.state = {
      checkResult: {},
      value: formValue[name] || formDefaultValue[name]
    };
    return _this;
  }

  FormControl.prototype.getCheckTrigger = function getCheckTrigger() {
    var checkTrigger = this.context.form.checkTrigger;

    return this.props.checkTrigger || checkTrigger;
  };

  FormControl.prototype.render = function render() {
    var _props = this.props,
        name = _props.name,
        Component = _props.accepter,
        classPrefix = _props.classPrefix,
        errorPlacement = _props.errorPlacement,
        errorMessage = _props.errorMessage,
        props = _objectWithoutProperties(_props, ['name', 'accepter', 'classPrefix', 'errorPlacement', 'errorMessage']);

    var _context$form2 = this.context.form,
        _context$form2$formVa = _context$form2.formValue,
        formValue = _context$form2$formVa === undefined ? {} : _context$form2$formVa,
        _context$form2$formDe = _context$form2.formDefaultValue,
        formDefaultValue = _context$form2$formDe === undefined ? {} : _context$form2$formDe;

    var unhandled = (0, _utils.getUnhandledProps)(FormControl, props);
    var addPrefix = (0, _utils.prefix)(classPrefix);
    var hasError = !!errorMessage;

    return React.createElement(
      'div',
      { className: addPrefix('wrapper') },
      React.createElement(Component, _extends({}, unhandled, {
        name: name,
        onChange: this.handleFieldChange,
        onBlur: this.handleFieldBlur,
        defaultValue: formDefaultValue[name],
        value: formValue[name]
      })),
      React.createElement(
        _ErrorMessage2.default,
        {
          show: hasError,
          className: addPrefix('message-wrapper'),
          placement: errorPlacement
        },
        errorMessage
      )
    );
  };

  return FormControl;
}(React.Component);

FormControl.defaultProps = {
  accepter: _Input2.default,
  errorPlacement: 'bottomLeft'
};
FormControl.contextTypes = {
  form: _propTypes2.default.object
};
FormControl.handledProps = ['accepter', 'checkTrigger', 'classPrefix', 'errorMessage', 'errorPlacement', 'name', 'onBlur', 'onChange'];
FormControl.propTypes = {
  name: _propTypes2.default.string.isRequired,
  checkTrigger: _propTypes2.default.oneOf(['change', 'blur', 'none']),
  accepter: function accepter() {
    return (typeof (React.ElementType == null ? {} : React.ElementType) === 'function' ? _propTypes2.default.instanceOf(React.ElementType == null ? {} : React.ElementType).isRequired : _propTypes2.default.any.isRequired).apply(this, arguments);
  },
  onChange: _propTypes2.default.func,
  onBlur: _propTypes2.default.func,
  classPrefix: _propTypes2.default.string,
  errorMessage: _propTypes2.default.node,
  errorPlacement: _propTypes2.default.oneOf(['bottomLeft', 'bottomRight', 'topLeft', 'topRight', 'leftTop', 'rightTop', 'leftBottom', 'rightBottom'])
};

var _initialiseProps = function _initialiseProps() {
  var _this2 = this;

  this.handleFieldChange = function (value, event) {
    var _props2 = _this2.props,
        name = _props2.name,
        onChange = _props2.onChange;
    var onFieldChange = _this2.context.form.onFieldChange;

    var checkTrigger = _this2.getCheckTrigger();
    var checkResult = _this2.handleFieldCheck(value, checkTrigger === 'change');
    _this2.setState({ checkResult: checkResult, value: value });
    onFieldChange(name, value, event);
    onChange && onChange(value, event);
  };

  this.handleFieldBlur = function (event) {
    var onBlur = _this2.props.onBlur;

    var checkTrigger = _this2.getCheckTrigger();
    _this2.handleFieldCheck(_this2.state.value, checkTrigger === 'blur');
    onBlur && onBlur(event);
  };

  this.handleFieldCheck = function (value, isCheckTrigger, callback) {
    var name = _this2.props.name;
    var _context$form3 = _this2.context.form,
        onFieldError = _context$form3.onFieldError,
        onFieldSuccess = _context$form3.onFieldSuccess,
        model = _context$form3.model;


    var checkResult = model.checkForField(name, value);

    if (isCheckTrigger) {
      if (checkResult.hasError) {
        onFieldError(name, checkResult.errorMessage, callback);
      } else {
        onFieldSuccess(name, callback);
      }
    }

    return checkResult;
  };
};

exports.default = (0, _utils.defaultProps)({
  classPrefix: 'form-control'
})(FormControl);