'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 _get = require('lodash/get');

var _get2 = _interopRequireDefault(_get);

var _reactIntl = require('react-intl');

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,
    LineInput = _cspaceInput.components.LineInput;


var messages = (0, _reactIntl.defineMessages)({
  prompt: {
    'id': 'passwordResetRequestForm.prompt',
    'defaultMessage': 'Enter your email address to request a password reset.'
  },
  submit: {
    'id': 'passwordResetRequestForm.submit',
    'defaultMessage': 'Submit'
  },
  success: {
    'id': 'passwordResetRequestForm.success',
    'defaultMessage': 'An email has been sent to {email}. Follow the instructions in the email to finish resetting your password.'
  },
  error: {
    'id': 'passwordResetRequestForm.error',
    'defaultMessage': 'An error occurred while attempting to request the password reset: {detail}'
  },
  errorNotFound: {
    'id': 'passwordResetRequestForm.errorNotFound',
    'defaultMessage': 'Could not locate an account associated with the email {email}.'
  },
  errorMissingEmail: {
    'id': 'passwordResetRequestForm.errorMissingEmail',
    'defaultMessage': 'Please enter an email address.'
  },
  errorInvalidEmail: {
    'id': 'passwordResetRequestForm.errorInvalidEmail',
    'defaultMessage': '{email} is not a valid email address.'
  }
});

var propTypes = {
  email: _propTypes2.default.string,
  requestReset: _propTypes2.default.func.isRequired
};

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

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

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

    _this.handleSubmit = _this.handleSubmit.bind(_this);
    _this.handleUsernameCommit = _this.handleUsernameCommit.bind(_this);

    _this.state = {
      isPending: false,
      email: props.email
    };
    return _this;
  }

  _createClass(PasswordResetRequestForm, [{
    key: 'handleSubmit',
    value: function handleSubmit(event) {
      var _this2 = this;

      event.preventDefault();

      var email = this.state.email;


      if (!email) {
        this.setState({
          error: {
            code: _errorCodes.ERR_MISSING_EMAIL
          }
        });

        return;
      }

      if (!(0, _validationHelpers.isValidEmail)(email)) {
        this.setState({
          error: {
            code: _errorCodes.ERR_INVALID_EMAIL
          }
        });

        return;
      }

      var requestReset = this.props.requestReset;


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

      requestReset(email).then(function () {
        _this2.setState({
          error: null,
          isPending: false,
          isSuccess: true
        });
      }).catch(function (error) {
        _this2.setState({
          error: error,
          isPending: false,
          isSuccess: false
        });
      });
    }
  }, {
    key: 'handleUsernameCommit',
    value: function handleUsernameCommit(path, value) {
      this.setState({
        email: value
      });
    }
  }, {
    key: 'renderError',
    value: function renderError() {
      var _state = this.state,
          email = _state.email,
          error = _state.error;


      if (!error) {
        return undefined;
      }

      var message = void 0;

      var values = {
        email: email
      };

      var code = error.code;


      if (code === _errorCodes.ERR_INVALID_EMAIL) {
        message = messages.errorInvalidEmail;
      } else if (code === _errorCodes.ERR_MISSING_EMAIL) {
        message = messages.errorMissingEmail;
      } else {
        var statusCode = (0, _get2.default)(error, ['response', 'status']);

        if (statusCode === 404) {
          message = messages.errorNotFound;
        }
      }

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

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


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

      return _react2.default.createElement(
        'form',
        { onSubmit: this.handleSubmit },
        _react2.default.createElement(
          'p',
          null,
          _react2.default.createElement(
            'label',
            { htmlFor: 'email' },
            _react2.default.createElement(_reactIntl.FormattedMessage, messages.prompt)
          )
        ),
        _react2.default.createElement(
          'div',
          null,
          _react2.default.createElement(LineInput, {
            autoComplete: 'email',
            id: 'email',
            name: 'email',
            type: 'text',
            value: email,
            onCommit: this.handleUsernameCommit
          })
        ),
        _react2.default.createElement(
          Button,
          { type: 'submit', disabled: isPending },
          _react2.default.createElement(_reactIntl.FormattedMessage, messages.submit)
        ),
        this.renderError()
      );
    }
  }]);

  return PasswordResetRequestForm;
}(_react.Component);

exports.default = PasswordResetRequestForm;


PasswordResetRequestForm.propTypes = propTypes;