'use strict';

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

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

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

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

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


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

var contextTypes = {
  config: _propTypes2.default.object
};

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

var defaultProps = {
  showForgotLink: true,
  showHeader: true
};

var LoginForm = function (_Component) {
  _inherits(LoginForm, _Component);

  function LoginForm(props) {
    _classCallCheck(this, LoginForm);

    var _this = _possibleConstructorReturn(this, (LoginForm.__proto__ || Object.getPrototypeOf(LoginForm)).call(this, 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
    };
    return _this;
  }

  _createClass(LoginForm, [{
    key: 'componentDidMount',
    value: function componentDidMount() {
      var 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();
      }
    }
  }, {
    key: 'componentWillReceiveProps',
    value: function componentWillReceiveProps(nextProps) {
      this.setState({
        username: nextProps.username
      });
    }
  }, {
    key: 'componentDidUpdate',
    value: function componentDidUpdate(prevProps) {
      var _props = this.props,
          error = _props.error,
          isSuccess = _props.isSuccess,
          username = _props.username,
          onSuccess = _props.onSuccess;
      var 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();
      }
    }
  }, {
    key: 'handlePasswordInputApi',
    value: function handlePasswordInputApi(api) {
      this.passwordInputApi = api;
    }
  }, {
    key: 'handleSubmit',
    value: function handleSubmit(event) {
      event.preventDefault();

      var login = this.props.login;
      var config = this.context.config;


      if (login) {
        var form = event.target;
        var username = form.username.value;
        var password = form.password.value;

        login(config, username, password);
      }
    }
  }, {
    key: 'handleUsernameInputApi',
    value: function handleUsernameInputApi(api) {
      this.usernameInputApi = api;
    }
  }, {
    key: 'handleUsernameChange',
    value: function handleUsernameChange(value) {
      this.setState({
        username: value
      });
    }
  }, {
    key: 'renderHeader',
    value: function renderHeader() {
      var showHeader = this.props.showHeader;


      if (!showHeader) {
        return null;
      }

      return _react2.default.createElement(
        'h2',
        null,
        _react2.default.createElement(_reactIntl.FormattedMessage, messages.title)
      );
    }
  }, {
    key: 'renderPrompt',
    value: function renderPrompt() {
      var _props2 = this.props,
          isExpired = _props2.isExpired,
          isPending = _props2.isPending,
          isSuccess = _props2.isSuccess;


      var messageKey = void 0;

      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])
      );
    }
  }, {
    key: 'renderButtonBar',
    value: function renderButtonBar() {
      var showForgotLink = this.props.showForgotLink;
      var username = this.state.username;


      var forgotLink = void 0;

      if (showForgotLink) {
        forgotLink = _react2.default.createElement(
          _reactRouterDom.Link,
          {
            to: {
              pathname: '/resetpw',
              state: {
                username: 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' })
      );
    }
  }, {
    key: 'renderForm',
    value: function renderForm() {
      var _props3 = this.props,
          formId = _props3.formId,
          intl = _props3.intl,
          isPending = _props3.isPending,
          isSuccess = _props3.isSuccess;


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

      var 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()
      );
    }
  }, {
    key: 'renderError',
    value: function renderError() {
      var _props4 = this.props,
          error = _props4.error,
          isPending = _props4.isPending;


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

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

      return _react2.default.createElement(_Notification2.default, {
        id: 'loginForm.error',
        items: [{
          message: messages[messageKey]
        }],
        showCloseButton: false,
        status: 'error'
      });
    }
  }, {
    key: 'render',
    value: function render() {
      return _react2.default.createElement(
        'div',
        { className: _LoginForm2.default.common },
        this.renderHeader(),
        this.renderPrompt(),
        this.renderForm(),
        this.renderError()
      );
    }
  }]);

  return LoginForm;
}(_react.Component);

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

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