"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = exports.BaseLoginForm = 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 _immutable = _interopRequireDefault(require("immutable"));

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

var _LoginButton = _interopRequireDefault(require("./LoginButton"));

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

var _LoginForm = _interopRequireDefault(require("../../../styles/cspace-ui/LoginForm.css"));

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

function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { 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; }

const {
  LineInput,
  PasswordInput
} = _cspaceInput.components;
const messages = (0, _reactIntl.defineMessages)({
  title: {
    "id": "loginForm.title",
    "defaultMessage": "Sign In"
  },
  prompt: {
    "id": "loginForm.prompt",
    "defaultMessage": "Please sign in to continue."
  },
  expiredPrompt: {
    "id": "loginForm.expiredPrompt",
    "defaultMessage": "Your session has expired. Please sign in again to continue."
  },
  pending: {
    "id": "loginForm.pending",
    "defaultMessage": "Signing in..."
  },
  success: {
    "id": "loginForm.success",
    "defaultMessage": "Sign in complete."
  },
  error: {
    "id": "loginForm.error",
    "defaultMessage": "Sign in failed."
  },
  ERR_INVALID_CREDENTIALS: {
    "id": "loginForm.ERR_INVALID_CREDENTIALS",
    "defaultMessage": "Sign in failed. Incorrect username/password."
  },
  ERR_NETWORK: {
    "id": "loginForm.ERR_NETWORK",
    "defaultMessage": "Sign in failed. Unable to reach the CollectionSpace server."
  },
  ERR_WRONG_TENANT: {
    "id": "loginForm.ERR_WRONG_TENANT",
    "defaultMessage": "Sign in failed. The user is not registered to this CollectionSpace tenant."
  },
  username: {
    "id": "loginForm.username",
    "defaultMessage": "Email"
  },
  password: {
    "id": "loginForm.password",
    "defaultMessage": "Password"
  },
  forgotPassword: {
    "id": "loginForm.forgotPassword",
    "defaultMessage": "Forgot password"
  }
});
const contextTypes = {
  config: _propTypes.default.shape({
    tenantId: _propTypes.default.string
  })
};
const propTypes = {
  formId: _propTypes.default.string,
  intl: _reactIntl.intlShape.isRequired,
  isExpired: _propTypes.default.bool,
  isPending: _propTypes.default.bool,
  isSuccess: _propTypes.default.bool,
  username: _propTypes.default.string,
  error: _propTypes.default.instanceOf(_immutable.default.Map),
  showForgotLink: _propTypes.default.bool,
  showHeader: _propTypes.default.bool,
  login: _propTypes.default.func,
  onSuccess: _propTypes.default.func
};
const defaultProps = {
  showForgotLink: true,
  showHeader: true
};

class LoginForm extends _react.Component {
  constructor(props) {
    super(props);
    this.handlePasswordInputApi = this.handlePasswordInputApi.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
    this.handleUsernameChange = this.handleUsernameChange.bind(this);
    this.handleUsernameInputApi = this.handleUsernameInputApi.bind(this);
    this.state = {
      username: props.username
    };
  }

  componentDidMount() {
    const {
      username
    } = this.props; // If there is a username, focus the password input. Otherwise, focus the username input.

    if (username && this.passwordInputApi) {
      this.passwordInputApi.focus();
    } else if (this.usernameInputApi) {
      this.usernameInputApi.focus();
    }
  } // eslint-disable-next-line camelcase


  UNSAFE_componentWillReceiveProps(nextProps) {
    this.setState({
      username: nextProps.username
    });
  }

  componentDidUpdate(prevProps) {
    const {
      error,
      isSuccess,
      username,
      onSuccess
    } = this.props;
    const {
      error: prevError,
      username: prevUsername
    } = prevProps;

    if (this.passwordInputApi) {
      // If the username has been set, focus the password.
      if (username && !prevUsername) {
        this.passwordInputApi.focus();
      } // If login fails, focus the password.


      if (error && !prevError) {
        this.passwordInputApi.focus();
      }
    }

    if (onSuccess && isSuccess && !prevProps.isSuccess) {
      onSuccess();
    }
  }

  handlePasswordInputApi(api) {
    this.passwordInputApi = api;
  }

  handleSubmit(event) {
    event.preventDefault();
    const {
      login
    } = this.props;
    const {
      config
    } = this.context;

    if (login) {
      const form = event.target;
      const username = form.username.value;
      const password = form.password.value;
      login(config, username, password);
    }
  }

  handleUsernameInputApi(api) {
    this.usernameInputApi = api;
  }

  handleUsernameChange(value) {
    this.setState({
      username: value
    });
  }

  renderHeader() {
    const {
      showHeader
    } = this.props;

    if (!showHeader) {
      return null;
    }

    return /*#__PURE__*/_react.default.createElement("h2", null, /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedMessage, messages.title));
  }

  renderPrompt() {
    const {
      isExpired,
      isPending,
      isSuccess
    } = this.props;
    let messageKey;

    if (isPending) {
      messageKey = 'pending';
    } else if (isSuccess) {
      messageKey = 'success';
    } else if (isExpired) {
      messageKey = 'expiredPrompt';
    } else {
      messageKey = 'prompt';
    }

    return /*#__PURE__*/_react.default.createElement("p", null, /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedMessage, messages[messageKey]));
  }

  renderButtonBar() {
    const {
      showForgotLink
    } = this.props;
    const {
      username
    } = this.state;
    let forgotLink;

    if (showForgotLink) {
      forgotLink = /*#__PURE__*/_react.default.createElement(_reactRouterDom.Link, {
        to: {
          pathname: '/resetpw',
          state: {
            username
          }
        }
      }, /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedMessage, messages.forgotPassword));
    } else {
      forgotLink = /*#__PURE__*/_react.default.createElement("div", null);
    }

    return /*#__PURE__*/_react.default.createElement("div", null, forgotLink, /*#__PURE__*/_react.default.createElement(_LoginButton.default, {
      type: "submit"
    }));
  }

  renderForm() {
    const {
      formId,
      intl,
      isPending,
      isSuccess
    } = this.props;

    if (isPending || isSuccess) {
      return null;
    }

    const {
      username
    } = this.state;
    return /*#__PURE__*/_react.default.createElement("form", {
      id: formId,
      onSubmit: this.handleSubmit
    }, /*#__PURE__*/_react.default.createElement(LineInput, {
      autoComplete: "username email",
      id: "username",
      placeholder: intl.formatMessage(messages.username),
      type: "text",
      value: username,
      api: this.handleUsernameInputApi,
      onChange: this.handleUsernameChange
    }), /*#__PURE__*/_react.default.createElement(PasswordInput, {
      autoComplete: "current-password",
      id: "password",
      placeholder: intl.formatMessage(messages.password),
      api: this.handlePasswordInputApi
    }), this.renderButtonBar());
  }

  renderError() {
    const {
      error,
      isPending
    } = this.props;

    if (isPending || !error) {
      return undefined;
    }

    const messageKey = error.get('code') || 'error';
    return /*#__PURE__*/_react.default.createElement(_Notification.default, {
      id: "loginForm.error",
      items: [{
        message: messages[messageKey]
      }],
      showCloseButton: false,
      status: "error"
    });
  }

  render() {
    const {
      isPending,
      isSuccess
    } = this.props;
    let className;

    if (isPending) {
      className = _LoginForm.default.pending;
    } else if (isSuccess) {
      className = _LoginForm.default.success;
    } else {
      className = _LoginForm.default.common;
    }

    return /*#__PURE__*/_react.default.createElement("div", {
      className: className
    }, this.renderHeader(), this.renderPrompt(), this.renderForm(), this.renderError());
  }

}

exports.BaseLoginForm = LoginForm;
LoginForm.propTypes = propTypes;
LoginForm.defaultProps = defaultProps;
LoginForm.contextTypes = contextTypes;

var _default = (0, _reactIntl.injectIntl)(LoginForm);

exports.default = _default;