"use strict";

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

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

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

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

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

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

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 _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; 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,
  PasswordInput
} = _cspaceInput.components;
const 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."
  }
});
const propTypes = {
  token: _propTypes.default.string.isRequired,
  reset: _propTypes.default.func.isRequired
};
const contextTypes = {
  intl: _reactIntl.intlShape
};

class PasswordResetForm extends _react.Component {
  constructor() {
    super();
    this.handleConfirmPasswordCommit = this.handleConfirmPasswordCommit.bind(this);
    this.handlePasswordCommit = this.handlePasswordCommit.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
    this.state = {};
  }

  handleConfirmPasswordCommit(path, value) {
    this.setState({
      confirmPassword: value
    });
  }

  handlePasswordCommit(path, value) {
    this.setState({
      password: value
    });
  }

  handleSubmit(event) {
    event.preventDefault();
    const {
      password,
      confirmPassword
    } = this.state;

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

    const {
      reset,
      token
    } = this.props;
    this.setState({
      error: null,
      isPending: true,
      isSuccess: false
    });
    reset(password, token).then(() => {
      this.setState({
        error: null,
        isPending: false,
        isSuccess: true
      });
    }).catch(error => {
      this.setState({
        error,
        isPending: false,
        isSuccess: false
      });
    });
  }

  renderError() {
    const {
      error
    } = this.state;
    const {
      intl
    } = this.context;

    if (!error) {
      return undefined;
    }

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

    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 {
      const statusCode = (0, _get.default)(error, ['response', 'status']);

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

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

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

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

  render() {
    const {
      isPending,
      isSuccess,
      password,
      confirmPassword
    } = this.state;
    const {
      intl
    } = this.context;
    const errorMessage = this.renderError();

    if (isSuccess) {
      const loginLink = _react.default.createElement(_reactRouterDom.Link, {
        to: "/login"
      }, intl.formatMessage(messages.loginLink));

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

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

}

exports.default = PasswordResetForm;
PasswordResetForm.propTypes = propTypes;
PasswordResetForm.contextTypes = contextTypes;