'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 _reactIntl = require('react-intl');

var _reactRouterDom = require('react-router-dom');

var _get = require('lodash/get');

var _get2 = _interopRequireDefault(_get);

var _cspaceInput = require('cspace-input');

var _Notification = require('../notification/Notification');

var _Notification2 = _interopRequireDefault(_Notification);

var _getErrorDescription = require('../../helpers/getErrorDescription');

var _getErrorDescription2 = _interopRequireDefault(_getErrorDescription);

var _validationHelpers = require('../../helpers/validationHelpers');

var _errorCodes = require('../../constants/errorCodes');

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

var Button = _cspaceInput.components.Button,
    PasswordInput = _cspaceInput.components.PasswordInput;


var messages = (0, _reactIntl.defineMessages)({
  prompt: {
    'id': 'passwordResetForm.prompt',
    'defaultMessage': 'Enter the new password for this account.'
  },
  password: {
    'id': 'passwordResetForm.password',
    'defaultMessage': 'Password'
  },
  confirmPassword: {
    'id': 'passwordResetForm.confirmPassword',
    'defaultMessage': 'Confirm password'
  },
  submit: {
    'id': 'passwordResetForm.submit',
    'defaultMessage': 'Submit'
  },
  success: {
    'id': 'passwordResetForm.success',
    'defaultMessage': 'Your password has been reset. {loginLink} to continue.'
  },
  loginLink: {
    'id': 'passwordResetForm.loginLink',
    'defaultMessage': 'Sign in'
  },
  newRequestLink: {
    'id': 'passwordResetForm.newRequestLink',
    'defaultMessage': 'make a new request'
  },
  error: {
    'id': 'passwordResetForm.error',
    'defaultMessage': 'An error occurred while attempting to reset the password: {detail}'
  },
  errorMissingPassword: {
    'id': 'passwordResetForm.errorMissingPassword',
    'defaultMessage': 'Please enter a new password.'
  },
  errorMissingConfirmation: {
    'id': 'passwordResetForm.errorMissingConfirmation',
    'defaultMessage': 'Please confirm the new password.'
  },
  errorNotConfirmed: {
    'id': 'passwordResetForm.errorNotConfirmed',
    'defaultMessage': 'The password was not correctly confirmed.'
  },
  errorInvalidPassword: {
    'id': 'passwordResetForm.errorInvalidPassword',
    'defaultMessage': 'The password must be between 8 and 24 characters.'
  },
  errorTokenExpired: {
    'id': 'passwordResetForm.errorTokenExpired',
    'defaultMessage': 'The password reset request has expired. Please {newRequestLink} to reset your password.'
  },
  errorTokenInvalid: {
    'id': 'passwordResetForm.errorTokenInvalid',
    'defaultMessage': 'The password reset request could not be validated. Please {newRequestLink} to reset your password.'
  }
});

var propTypes = {
  token: _propTypes2.default.string.isRequired,
  reset: _propTypes2.default.func.isRequired
};

var contextTypes = {
  intl: _reactIntl.intlShape
};

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

  function PasswordResetForm() {
    _classCallCheck(this, PasswordResetForm);

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

    _this.handleConfirmPasswordCommit = _this.handleConfirmPasswordCommit.bind(_this);
    _this.handlePasswordCommit = _this.handlePasswordCommit.bind(_this);
    _this.handleSubmit = _this.handleSubmit.bind(_this);

    _this.state = {};
    return _this;
  }

  _createClass(PasswordResetForm, [{
    key: 'handleConfirmPasswordCommit',
    value: function handleConfirmPasswordCommit(path, value) {
      this.setState({
        confirmPassword: value
      });
    }
  }, {
    key: 'handlePasswordCommit',
    value: function handlePasswordCommit(path, value) {
      this.setState({
        password: value
      });
    }
  }, {
    key: 'handleSubmit',
    value: function handleSubmit(event) {
      var _this2 = this;

      event.preventDefault();

      var _state = this.state,
          password = _state.password,
          confirmPassword = _state.confirmPassword;


      if (!password) {
        this.setState({
          error: {
            code: _errorCodes.ERR_MISSING_PW
          }
        });

        return;
      }

      if (!confirmPassword) {
        this.setState({
          error: {
            code: _errorCodes.ERR_MISSING_PW_CONFIRM
          }
        });

        return;
      }

      if (password !== confirmPassword) {
        this.setState({
          error: {
            code: _errorCodes.ERR_PW_NOT_CONFIRMED
          }
        });

        return;
      }

      if (!(0, _validationHelpers.isValidPassword)(password)) {
        this.setState({
          error: {
            code: _errorCodes.ERR_INVALID_PW
          }
        });

        return;
      }

      var _props = this.props,
          reset = _props.reset,
          token = _props.token;


      this.setState({
        error: null,
        isPending: true,
        isSuccess: false
      });

      reset(password, token).then(function () {
        _this2.setState({
          error: null,
          isPending: false,
          isSuccess: true
        });
      }).catch(function (error) {
        _this2.setState({
          error: error,
          isPending: false,
          isSuccess: false
        });
      });
    }
  }, {
    key: 'renderError',
    value: function renderError() {
      var error = this.state.error;
      var intl = this.context.intl;


      if (!error) {
        return undefined;
      }

      var message = void 0;

      var values = {};

      var code = error.code;


      if (code === _errorCodes.ERR_MISSING_PW) {
        message = messages.errorMissingPassword;
      } else if (code === _errorCodes.ERR_MISSING_PW_CONFIRM) {
        message = messages.errorMissingConfirmation;
      } else if (code === _errorCodes.ERR_PW_NOT_CONFIRMED) {
        message = messages.errorNotConfirmed;
      } else if (code === _errorCodes.ERR_INVALID_PW) {
        message = messages.errorInvalidPassword;
      } else {
        var statusCode = (0, _get2.default)(error, ['response', 'status']);

        if (statusCode === 400 || statusCode === 500) {
          var data = (0, _get2.default)(error, ['response', 'data']);

          if (/token .* not valid/.test(data)) {
            message = messages.errorTokenInvalid;

            values.newRequestLink = _react2.default.createElement(
              _reactRouterDom.Link,
              { to: '/resetpw' },
              intl.formatMessage(messages.newRequestLink)
            );
          } else if (/token .* expired/.test(data)) {
            message = messages.errorTokenExpired;

            values.newRequestLink = _react2.default.createElement(
              _reactRouterDom.Link,
              { to: '/resetpw' },
              intl.formatMessage(messages.newRequestLink)
            );
          }
        }
      }

      if (!message) {
        message = messages.error;
        values.detail = (0, _getErrorDescription2.default)(error);
      }

      return _react2.default.createElement(_Notification2.default, {
        id: 'passwordResetForm.error',
        items: [{
          message: message,
          values: values
        }],
        showCloseButton: false,
        status: 'error'
      });
    }
  }, {
    key: 'render',
    value: function render() {
      var _state2 = this.state,
          isPending = _state2.isPending,
          isSuccess = _state2.isSuccess,
          password = _state2.password,
          confirmPassword = _state2.confirmPassword;
      var intl = this.context.intl;


      var errorMessage = this.renderError();

      if (isSuccess) {
        var loginLink = _react2.default.createElement(
          _reactRouterDom.Link,
          { to: '/login' },
          intl.formatMessage(messages.loginLink)
        );

        return _react2.default.createElement(_reactIntl.FormattedMessage, _extends({}, messages.success, { values: { loginLink: loginLink } }));
      }

      return _react2.default.createElement(
        'form',
        { onSubmit: this.handleSubmit },
        _react2.default.createElement(
          'p',
          null,
          _react2.default.createElement(_reactIntl.FormattedMessage, messages.prompt)
        ),
        _react2.default.createElement(
          'div',
          null,
          _react2.default.createElement(PasswordInput, {
            autoComplete: 'new-password',
            name: 'password',
            placeholder: intl.formatMessage(messages.password),
            value: password,
            onCommit: this.handlePasswordCommit
          })
        ),
        _react2.default.createElement(
          'div',
          null,
          _react2.default.createElement(PasswordInput, {
            autoComplete: 'new-password',
            name: 'confirmPassword',
            placeholder: intl.formatMessage(messages.confirmPassword),
            value: confirmPassword,
            onCommit: this.handleConfirmPasswordCommit
          })
        ),
        _react2.default.createElement(
          Button,
          { type: 'submit', disabled: isPending },
          _react2.default.createElement(_reactIntl.FormattedMessage, messages.submit)
        ),
        errorMessage
      );
    }
  }]);

  return PasswordResetForm;
}(_react.Component);

exports.default = PasswordResetForm;


PasswordResetForm.propTypes = propTypes;
PasswordResetForm.contextTypes = contextTypes;