'use strict';

exports.__esModule = true;

var _omit2 = require('lodash/omit');

var _omit3 = _interopRequireDefault(_omit2);

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

var _isUndefined3 = _interopRequireDefault(_isUndefined2);

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 _rsuiteSchema = require('rsuite-schema');

var _classnames = require('classnames');

var _classnames2 = _interopRequireDefault(_classnames);

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

var _prefix = require('./utils/prefix');

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

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

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

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

    _initialiseProps.call(_this);

    _this.state = {
      formError: props.formError || {},
      formValue: props.formDefaultValue
    };
    return _this;
  }

  Form.prototype.getChildContext = function getChildContext() {
    var _props = this.props,
        formDefaultValue = _props.formDefaultValue,
        formValue = _props.formValue,
        model = _props.model,
        checkTrigger = _props.checkTrigger;

    var formError = this.getFormError();
    return {
      form: {
        onFieldChange: this.handleFieldChange,
        onFieldError: this.handleFieldError,
        onFieldSuccess: this.handleFieldSuccess,
        checkTrigger: checkTrigger,
        formValue: formValue,
        formDefaultValue: formDefaultValue,
        formError: formError,
        model: model
      }
    };
  };

  Form.prototype.getFormValue = function getFormValue() {
    var formValue = this.props.formValue;

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

  Form.prototype.getFormError = function getFormError() {
    var formError = this.props.formError;

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

  /**
   * public APIs
   */


  /**
   * public APIs
   */
  Form.prototype.cleanErrors = function cleanErrors(callback) {
    this.setState({ formError: {} }, callback);
  };

  /**
   * public APIs
   */


  Form.prototype.resetErrors = function resetErrors() {
    var formError = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
    var callback = arguments[1];

    this.setState({ formError: formError }, callback);
  };

  Form.prototype.render = function render() {
    var _props2 = this.props,
        layout = _props2.layout,
        classPrefix = _props2.classPrefix,
        fluid = _props2.fluid,
        className = _props2.className,
        props = _objectWithoutProperties(_props2, ['layout', 'classPrefix', 'fluid', 'className']);

    var addPrefix = (0, _utils.prefix)(classPrefix);
    var clesses = (0, _classnames2.default)(classPrefix, addPrefix(layout), className, addPrefix(fluid && layout === 'vertical' ? 'fluid' : 'fixed-width'));
    var unhandled = (0, _utils.getUnhandledProps)(Form, props);

    return React.createElement('form', _extends({}, unhandled, { onSubmit: function onSubmit(e) {
        return e.preventDefault();
      }, className: clesses }));
  };

  return Form;
}(React.Component);

Form.defaultProps = {
  classPrefix: (0, _prefix.defaultClassPrefix)('form'),
  model: (0, _rsuiteSchema.SchemaModel)({}),
  layout: 'vertical',
  formDefaultValue: {},
  checkDelay: 500,
  checkTrigger: 'change'
};
Form.childContextTypes = {
  form: _propTypes2.default.object.isRequired
};
Form.handledProps = ['checkDelay', 'checkTrigger', 'className', 'classPrefix', 'fluid', 'formDefaultValue', 'formError', 'formValue', 'layout', 'model', 'onChange', 'onCheck', 'onError'];
Form.propTypes = {
  className: _propTypes2.default.string,
  layout: _propTypes2.default.oneOf(['horizontal', 'vertical', 'inline']),
  fluid: _propTypes2.default.bool,
  formValue: _propTypes2.default.object,
  formDefaultValue: _propTypes2.default.object,
  formError: _propTypes2.default.object,
  checkDelay: _propTypes2.default.number,
  checkTrigger: _propTypes2.default.oneOf(['change', 'blur', 'none']),
  onChange: _propTypes2.default.func,
  onError: _propTypes2.default.func,
  onCheck: _propTypes2.default.func,
  model: function model(props, propName, componentName) {
    if (!Object.prototype.hasOwnProperty.call(props, propName)) {
      throw new Error('Prop `' + propName + '` has type \'any\' or \'mixed\', but was not provided to `' + componentName + '`. Pass undefined or any other value.');
    }
  },
  classPrefix: _propTypes2.default.string.isRequired
};

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

  this.check = function (callback) {
    var formValue = _this2.getFormValue() || {};
    var _props3 = _this2.props,
        model = _props3.model,
        onCheck = _props3.onCheck,
        onError = _props3.onError;

    var formError = {};
    var errorCount = 0;

    Object.keys(model.schema).forEach(function (key) {
      var checkResult = model.checkForField(key, formValue[key]);
      if (checkResult.hasError === true) {
        errorCount += 1;
        formError[key] = checkResult.errorMessage;
      }
    });

    _this2.setState({ formError: formError });
    onCheck && onCheck(formError);
    callback && callback(formError);
    if (errorCount > 0) {
      onError && onError(formError);
      return false;
    }

    return true;
  };

  this.handleFieldError = function (name, errorMessage) {
    var _extends2;

    var _props4 = _this2.props,
        onError = _props4.onError,
        onCheck = _props4.onCheck;

    var formError = _extends({}, _this2.state.formError, (_extends2 = {}, _extends2[name] = errorMessage, _extends2));

    _this2.setState({ formError: formError }, function () {
      onError && onError(formError);
      onCheck && onCheck(formError);
    });
  };

  this.handleFieldSuccess = function (name) {
    var onCheck = _this2.props.onCheck;

    var formError = (0, _omit3.default)(_this2.state.formError, [name]);
    _this2.setState({ formError: formError }, function () {
      onCheck && onCheck(formError);
    });
  };

  this.handleFieldChange = function (name, value, event) {
    var _extends3;

    var onChange = _this2.props.onChange;

    var formValue = _this2.getFormValue();
    var nextFormValue = _extends({}, formValue, (_extends3 = {}, _extends3[name] = value, _extends3));
    _this2.setState({
      formValue: nextFormValue
    });
    onChange && onChange(nextFormValue, event);
  };
};

exports.default = Form;