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

const Button = _cspaceInput.components.Button,
      LineInput = _cspaceInput.components.LineInput;


const 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.'
  }
});

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

class PasswordResetRequestForm extends _react.Component {
  constructor(props) {
    super(props);

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

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

  handleSubmit(event) {
    event.preventDefault();

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

    const requestReset = this.props.requestReset;


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

    requestReset(email).then(() => {
      this.setState({
        error: null,
        isPending: false,
        isSuccess: true
      });
    }).catch(error => {
      this.setState({
        error,
        isPending: false,
        isSuccess: false
      });
    });
  }

  handleUsernameCommit(path, value) {
    this.setState({
      email: value
    });
  }

  renderError() {
    var _state = this.state;
    const email = _state.email,
          error = _state.error;


    if (!error) {
      return undefined;
    }

    let message;

    const values = {
      email
    };

    const code = error.code;


    if (code === _errorCodes.ERR_INVALID_EMAIL) {
      message = messages.errorInvalidEmail;
    } else if (code === _errorCodes.ERR_MISSING_EMAIL) {
      message = messages.errorMissingEmail;
    } else {
      const 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,
        values
      }],
      showCloseButton: false,
      status: 'error'
    });
  }

  render() {
    var _state2 = this.state;
    const isSuccess = _state2.isSuccess,
          isPending = _state2.isPending,
          email = _state2.email;


    if (isSuccess) {
      return _react2.default.createElement(_reactIntl.FormattedMessage, _extends({}, messages.success, { values: { 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()
    );
  }
}

exports.default = PasswordResetRequestForm;
PasswordResetRequestForm.propTypes = propTypes;