'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

var _propTypes = require('prop-types');

var _propTypes2 = _interopRequireDefault(_propTypes);

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

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

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

var _LoginButton = require('./LoginButton');

var _LoginButton2 = _interopRequireDefault(_LoginButton);

var _Notification = require('../notification/Notification');

var _Notification2 = _interopRequireDefault(_Notification);

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

var _LoginForm2 = _interopRequireDefault(_LoginForm);

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

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


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: _propTypes2.default.object
};

const propTypes = {
  formId: _propTypes2.default.string,
  intl: _propTypes2.default.object.isRequired,
  isExpired: _propTypes2.default.bool,
  isPending: _propTypes2.default.bool,
  isSuccess: _propTypes2.default.bool,
  username: _propTypes2.default.string,
  error: _propTypes2.default.object,
  showForgotLink: _propTypes2.default.bool,
  showHeader: _propTypes2.default.bool,
  login: _propTypes2.default.func,
  onSuccess: _propTypes2.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.username;

    // 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();
    }
  }

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

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


    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.login;
    const config = this.context.config;


    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.showHeader;


    if (!showHeader) {
      return null;
    }

    return _react2.default.createElement(
      'h2',
      null,
      _react2.default.createElement(_reactIntl.FormattedMessage, messages.title)
    );
  }

  renderPrompt() {
    var _props2 = this.props;
    const isExpired = _props2.isExpired,
          isPending = _props2.isPending,
          isSuccess = _props2.isSuccess;


    let messageKey;

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

    return _react2.default.createElement(
      'p',
      null,
      _react2.default.createElement(_reactIntl.FormattedMessage, messages[messageKey])
    );
  }

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


    let forgotLink;

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

    return _react2.default.createElement(
      'div',
      null,
      forgotLink,
      _react2.default.createElement(_LoginButton2.default, { type: 'submit' })
    );
  }

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


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

    const username = this.state.username;


    return _react2.default.createElement(
      'form',
      { id: formId, onSubmit: this.handleSubmit },
      _react2.default.createElement(LineInput, {
        autoComplete: 'username email',
        name: 'username',
        placeholder: intl.formatMessage(messages.username),
        type: 'text',
        value: username,
        api: this.handleUsernameInputApi,
        onChange: this.handleUsernameChange
      }),
      _react2.default.createElement(PasswordInput, {
        autoComplete: 'current-password',
        name: 'password',
        placeholder: intl.formatMessage(messages.password),
        api: this.handlePasswordInputApi
      }),
      this.renderButtonBar()
    );
  }

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


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

    const messageKey = error.get('code') || 'error';

    return _react2.default.createElement(_Notification2.default, {
      id: 'loginForm.error',
      items: [{
        message: messages[messageKey]
      }],
      showCloseButton: false,
      status: 'error'
    });
  }

  render() {
    return _react2.default.createElement(
      'div',
      { className: _LoginForm2.default.common },
      this.renderHeader(),
      this.renderPrompt(),
      this.renderForm(),
      this.renderError()
    );
  }
}

LoginForm.propTypes = propTypes;
LoginForm.defaultProps = defaultProps;
LoginForm.contextTypes = contextTypes;

exports.default = (0, _reactIntl.injectIntl)(LoginForm);