"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;

var _react = _interopRequireWildcard(require("react"));

var _propTypes = _interopRequireDefault(require("prop-types"));

var _get = _interopRequireDefault(require("lodash/get"));

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

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

var _Notification = _interopRequireDefault(require("../notification/Notification"));

var _getErrorDescription = _interopRequireDefault(require("../../helpers/getErrorDescription"));

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

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

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

function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function _getRequireWildcardCache() { return cache; }; return cache; }

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }

function _extends() { _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; }; return _extends.apply(this, arguments); }

const {
  Button,
  LineInput
} = _cspaceInput.components;
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: _propTypes.default.string,
  requestReset: _propTypes.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;

    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;
    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() {
    const {
      email,
      error
    } = this.state;

    if (!error) {
      return undefined;
    }

    let message;
    const values = {
      email
    };
    const {
      code
    } = error;

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

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

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

    return _react.default.createElement(_Notification.default, {
      id: "passwordResetRequestForm.error",
      items: [{
        message,
        values
      }],
      showCloseButton: false,
      status: "error"
    });
  }

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

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

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

}

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