'use strict';

Object.defineProperty(exports, "__esModule", {
  value: 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 _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 _react = require('react');

var _react2 = _interopRequireDefault(_react);

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

var _propTypes2 = _interopRequireDefault(_propTypes);

var _LoginCardInput = require('./LoginCardInput');

var _LoginCardInput2 = _interopRequireDefault(_LoginCardInput);

var _helpers = require('../../../../common/helpers');

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

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return 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; }

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

  function LoginCardWithValidation() {
    var _ref;

    var _temp, _this, _ret;

    _classCallCheck(this, LoginCardWithValidation);

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

    return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_ref = LoginCardWithValidation.__proto__ || Object.getPrototypeOf(LoginCardWithValidation)).call.apply(_ref, [this].concat(args))), _this), _this.state = {
      usernameField: {
        value: '',
        errorType: null,
        isFocused: false,
        showError: false
      },
      passwordField: {
        value: '',
        errorType: null,
        warningType: null,
        isFocused: false,
        showError: false
      },
      isCapsLock: false,
      form: {
        showError: false,
        submitError: _this.props.submitError,
        disableSubmit: _this.props.disableSubmit,
        isSubmitting: _this.props.isSubmitting
      }
    }, _this.onInputChange = function (e, inputType) {
      _this.props[inputType].onChange && _this.props[inputType].onChange(e);
      _this.setState(_defineProperty({}, inputType, _extends({}, _this.state[inputType], {
        value: e.target.value,
        showError: false
      })));
    }, _this.onInputFocus = function (e, inputType) {
      _this.props[inputType].onFocus && _this.props[inputType].onFocus(e);
      _this.setState(_defineProperty({}, inputType, _extends({}, _this.state[inputType], {
        isFocused: true,
        showError: false
      })));
    }, _this.onInputBlur = function (e, inputType) {
      var _this$setState3;

      _this.props[inputType].onBlur && _this.props[inputType].onBlur(e);
      _this.setState((_this$setState3 = {}, _defineProperty(_this$setState3, inputType, _extends({}, _this.state[inputType], {
        isFocused: false,
        showError: false
      })), _defineProperty(_this$setState3, 'isCapsLock', false), _this$setState3));
    }, _this.onKeyPress = function (e, inputType) {
      _this.props[inputType].onMouseEnter && _this.props[inputType].onMouseEnter(e);
      _this.handleCapsLock(e);
    }, _this.onSubmit = function (e) {
      e.preventDefault();
      if (_this.isFormValid()) {
        var _this$props = _this.props,
            onSubmit = _this$props.onSubmit,
            submitError = _this$props.submitError;

        onSubmit && onSubmit(e);
        submitError && _this.setState({
          form: _extends({}, _this.state.form, {
            showError: true,
            error: submitError,
            disableSubmit: true,
            isSubmitting: true
          })
        });
      } else {
        _this.handleOnInputErrors();
      }
    }, _this.getModifiedProps = function () {
      var _this$props2 = _this.props,
          usernameField = _this$props2.usernameField,
          passwordField = _this$props2.passwordField;

      var passwordFieldWarningType = _this.state.isCapsLock ? 'capsLock' : _this.state.passwordField.warningType;
      return {
        usernameField: _extends({}, usernameField, {
          onChange: function onChange(e) {
            return _this.onInputChange(e, 'usernameField');
          },
          onFocus: function onFocus(e) {
            return _this.onInputFocus(e, 'usernameField');
          },
          onBlur: function onBlur(e) {
            return _this.onInputBlur(e, 'usernameField');
          },
          onKeyPress: function onKeyPress(e) {
            return _this.onKeyPress(e, 'usernameField');
          },
          error: usernameField.errors[_this.state.usernameField.errorType],
          showError: _this.state.usernameField.showError
        }),
        passwordField: _extends({}, passwordField, {
          onChange: function onChange(e) {
            return _this.onInputChange(e, 'passwordField');
          },
          onFocus: function onFocus(e) {
            return _this.onInputFocus(e, 'passwordField');
          },
          onBlur: function onBlur(e) {
            return _this.onInputBlur(e, 'passwordField');
          },
          onKeyPress: function onKeyPress(e) {
            return _this.onKeyPress(e, 'passwordField');
          },
          warning: passwordField.warnings[passwordFieldWarningType],
          showWarning: _this.state.passwordField.isFocused && _this.state.isCapsLock,
          error: passwordField.errors[_this.state.passwordField.errorType],
          showError: _this.state.passwordField.showError
        }),
        onSubmit: function onSubmit(e) {
          return _this.onSubmit(e);
        },
        showError: _this.state.form.showError,
        disableSubmit: _this.state.form.disableSubmit,
        isSubmitting: _this.state.form.isSubmitting
      };
    }, _this.handleOnInputErrors = function () {
      var _this$state = _this.state,
          usernameField = _this$state.usernameField,
          passwordField = _this$state.passwordField;

      if (usernameField.value) {
        !_this.isUserNameValid() && _this.handleOnInvalidUsername();
      } else {
        _this.handleOnEmptyInput('usernameField');
      }

      if (passwordField.value) {
        _this.isPasswordShort() && _this.handleOnPasswordTooShort();
      } else {
        _this.handleOnEmptyInput('passwordField');
      }

      _this.hideSubmitError();
    }, _this.isFormValid = function () {
      return !!_this.state.usernameField.value && !!_this.state.passwordField.value && !_this.isPasswordShort() && _this.isUserNameValid();
    }, _this.isPasswordShort = function () {
      var passwordMinLength = _this.props.passwordField.minLength;
      var currentPasswordLength = _this.state.passwordField.value.length;

      return passwordMinLength > 0 && currentPasswordLength < passwordMinLength;
    }, _this.hideSubmitError = function () {
      _this.setState({
        form: _extends({}, _this.state.form, {
          showError: false
        })
      });
    }, _this.handleOnPasswordTooShort = function () {
      _this.setState({
        passwordField: _extends({}, _this.state.passwordField, {
          errorType: 'short',
          showError: true
        })
      });
    }, _this.handleOnInvalidUsername = function (error) {
      _this.setState({
        usernameField: _extends({}, _this.state.usernameField, {
          errorType: 'invalid',
          showError: true
        })
      });
    }, _this.handleOnEmptyInput = function (inputType) {
      _this.setState(_defineProperty({}, inputType, _extends({}, _this.state[inputType], {
        errorType: 'empty',
        showError: true
      })));
    }, _this.toggleCapsLock = function (e) {
      if (!_this.state.passwordField.value) {
        return;
      }
      e.key === _helpers.KEYS.CAPSLOCK && _this.setState({
        isCapsLock: !_this.state.isCapsLock
      });
    }, _this.handleCapsLock = function (e) {
      var keyCode = e.keyCode ? e.keyCode : e.which;
      var shiftKey = e.shiftKey ? e.shiftKey : keyCode === _helpers.KEY_CODES.SHIFT;
      var isCapsLock = keyCode >= _helpers.KEY_CODES.A && keyCode <= _helpers.KEY_CODES.Z && !shiftKey || keyCode >= _helpers.KEY_CODES.NUMPAD['0'] && keyCode <= _helpers.KEY_CODES.F11 && shiftKey;
      _this.setState({
        isCapsLock: isCapsLock
      });
    }, _this.isUserNameValid = function () {
      var userType = _this.props.usernameField.type;

      if (userType === 'email') {
        var mailAddress = _this.state.usernameField.value;
        var atPos = mailAddress.indexOf('@');
        var dotPos = mailAddress.lastIndexOf('.');
        return atPos > 1 && dotPos - atPos > 2 && atPos < dotPos;
      }
      return true;
    }, _temp), _possibleConstructorReturn(_this, _ret);
  }

  _createClass(LoginCardWithValidation, [{
    key: 'componentDidMount',
    value: function componentDidMount() {
      window.addEventListener('keyup', this.toggleCapsLock);
    }
  }, {
    key: 'componentWillUnmount',
    value: function componentWillUnmount() {
      window.removeEventListener('keyup', this.toggleCapsLock);
    }
  }, {
    key: 'render',
    value: function render() {
      var _props = this.props,
          validate = _props.validate,
          children = _props.children;

      return validate ? _react2.default.cloneElement(children, _extends({}, this.props, this.getModifiedProps())) : _react2.default.cloneElement(children, _extends({}, this.props));
    }
  }]);

  return LoginCardWithValidation;
}(_react2.default.Component);

LoginCardWithValidation.propTypes = {
  validate: _propTypes2.default.bool,
  children: _propTypes2.default.node.isRequired,
  usernameField: _propTypes2.default.shape(_extends({}, _LoginCardInput2.default.propTypes, {
    errors: _propTypes2.default.object
  })),
  passwordField: _propTypes2.default.shape(_extends({}, _LoginCardInput2.default.propTypes, {
    errors: _propTypes2.default.object,
    warnings: _propTypes2.default.object,
    minLength: _propTypes2.default.number
  })),
  onSubmit: _propTypes2.default.func,
  submitError: _propTypes2.default.oneOfType([_propTypes2.default.string, _propTypes2.default.node]),
  disableSubmit: _propTypes2.default.bool,
  isSubmitting: _propTypes2.default.bool
};

LoginCardWithValidation.defaultProps = {
  validate: true,
  usernameField: _extends({}, _LoginCardInput2.default.defaultProps.usernameField),
  passwordField: _extends({}, _LoginCardInput2.default.defaultProps.passwordField),
  onSubmit: function onSubmit(e) {
    return e.target.submit();
  },
  submitError: null,
  disableSubmit: false,
  isSubmitting: false
};

exports.default = LoginCardWithValidation;