"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;
var _base = _interopRequireDefault(require("@emotion/styled/base"));
var _partial2 = _interopRequireDefault(require("lodash/partial"));
var _propTypes = _interopRequireDefault(require("prop-types"));
var _react = _interopRequireDefault(require("react"));
var _decapCmsUiDefault = require("decap-cms-ui-default");
var _react2 = require("@emotion/react");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : String(i); }
function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
function _EMOTION_STRINGIFIED_CSS_ERROR__() { return "You have tried to stringify object returned from `css` function. It isn't supposed to be used directly (e.g. as value of the `className` prop), but rather handed to emotion so it can handle it (e.g. as value of `css` prop)."; }
const LoginButton = /*#__PURE__*/(0, _base.default)("button", {
  target: "e1fncu5t3",
  label: "LoginButton"
})(_decapCmsUiDefault.buttons.button, ";", _decapCmsUiDefault.shadows.dropDeep, ";", _decapCmsUiDefault.buttons.default, ";", _decapCmsUiDefault.buttons.gray, ";padding:0 30px;display:block;margin-top:20px;margin-left:auto;" + (process.env.NODE_ENV === "production" ? "" : "/*# sourceMappingURL=data:application/json;charset=utf-8;base64,[encoded data, 8124 characters] */"));
const AuthForm = /*#__PURE__*/(0, _base.default)("form", {
  target: "e1fncu5t2",
  label: "AuthForm"
})(process.env.NODE_ENV === "production" ? {
  name: "bjv45a",
  styles: "width:350px;margin-top:-80px"
} : {
  name: "bjv45a",
  styles: "width:350px;margin-top:-80px",
  map: "/*# sourceMappingURL=data:application/json;charset=utf-8;base64,[encoded data, 8128 characters] */",
  toString: _EMOTION_STRINGIFIED_CSS_ERROR__
});
const AuthInput = /*#__PURE__*/(0, _base.default)("input", {
  target: "e1fncu5t1",
  label: "AuthInput"
})("background-color:", _decapCmsUiDefault.colorsRaw.white, ";border-radius:", _decapCmsUiDefault.lengths.borderRadius, ";font-size:14px;padding:10px;margin-bottom:15px;margin-top:6px;width:100%;position:relative;z-index:", _decapCmsUiDefault.zIndex.zIndex1, ";&:focus{outline:none;box-shadow:inset 0 0 0 2px ", _decapCmsUiDefault.colors.active, ";}" + (process.env.NODE_ENV === "production" ? "" : "/*# sourceMappingURL=data:application/json;charset=utf-8;base64,[encoded data, 8128 characters] */"));
const ErrorMessage = /*#__PURE__*/(0, _base.default)("p", {
  target: "e1fncu5t0",
  label: "ErrorMessage"
})("color:", _decapCmsUiDefault.colors.errorText, ";" + (process.env.NODE_ENV === "production" ? "" : "/*# sourceMappingURL=data:application/json;charset=utf-8;base64,[encoded data, 8128 characters] */"));
let component = null;
if (window.netlifyIdentity) {
  window.netlifyIdentity.on('login', user => {
    component && component.handleIdentityLogin(user);
  });
  window.netlifyIdentity.on('logout', () => {
    component && component.handleIdentityLogout();
  });
  window.netlifyIdentity.on('error', err => {
    component && component.handleIdentityError(err);
  });
}
class GitGatewayAuthenticationPage extends _react.default.Component {
  constructor(props) {
    super(props);
    _defineProperty(this, "handleIdentityLogin", user => {
      this.props.onLogin(user);
      window.netlifyIdentity.close();
    });
    _defineProperty(this, "handleIdentityLogout", () => {
      window.netlifyIdentity.open();
    });
    _defineProperty(this, "handleIdentityError", err => {
      var _err$message;
      if (err !== null && err !== void 0 && (_err$message = err.message) !== null && _err$message !== void 0 && _err$message.match(/^Failed to load settings from.+\.netlify\/identity$/)) {
        window.netlifyIdentity.close();
        this.setState({
          errors: {
            identity: this.props.t('auth.errors.identitySettings')
          }
        });
      }
    });
    _defineProperty(this, "handleIdentity", () => {
      const user = window.netlifyIdentity.currentUser();
      if (user) {
        this.props.onLogin(user);
      } else {
        window.netlifyIdentity.open();
      }
    });
    _defineProperty(this, "state", {
      email: '',
      password: '',
      errors: {}
    });
    _defineProperty(this, "handleChange", (name, e) => {
      this.setState(_objectSpread(_objectSpread({}, this.state), {}, {
        [name]: e.target.value
      }));
    });
    _defineProperty(this, "handleLogin", async e => {
      e.preventDefault();
      const {
        email,
        password
      } = this.state;
      const {
        t
      } = this.props;
      const errors = {};
      if (!email) {
        errors.email = t('auth.errors.email');
      }
      if (!password) {
        errors.password = t('auth.errors.password');
      }
      if (Object.keys(errors).length > 0) {
        this.setState({
          errors
        });
        return;
      }
      try {
        const client = await GitGatewayAuthenticationPage.authClient();
        const user = await client.login(this.state.email, this.state.password, true);
        this.props.onLogin(user);
      } catch (error) {
        this.setState({
          errors: {
            server: error.description || error.msg || error
          },
          loggingIn: false
        });
      }
    });
    component = this;
  }
  componentDidMount() {
    if (!this.loggedIn && window.netlifyIdentity && window.netlifyIdentity.currentUser()) {
      this.props.onLogin(window.netlifyIdentity.currentUser());
      window.netlifyIdentity.close();
    }
  }
  componentWillUnmount() {
    component = null;
  }
  render() {
    const {
      errors
    } = this.state;
    const {
      error,
      inProgress,
      config,
      t
    } = this.props;
    if (window.netlifyIdentity) {
      if (errors.identity) {
        return (0, _react2.jsx)(_decapCmsUiDefault.AuthenticationPage, {
          logoUrl: config.logo_url,
          siteUrl: config.site_url,
          onLogin: this.handleIdentity,
          renderPageContent: () => (0, _react2.jsx)("a", {
            href: "https://docs.netlify.com/visitor-access/git-gateway/#setup-and-settings",
            target: "_blank",
            rel: "noopener noreferrer"
          }, errors.identity),
          t: t
        });
      } else {
        return (0, _react2.jsx)(_decapCmsUiDefault.AuthenticationPage, {
          logoUrl: config.logo_url,
          siteUrl: config.site_url,
          onLogin: this.handleIdentity,
          renderButtonContent: () => t('auth.loginWithNetlifyIdentity'),
          t: t
        });
      }
    }
    return (0, _react2.jsx)(_decapCmsUiDefault.AuthenticationPage, {
      logoUrl: config.logo_url,
      siteUrl: config.site_url,
      renderPageContent: () => (0, _react2.jsx)(AuthForm, {
        onSubmit: this.handleLogin
      }, !error ? null : (0, _react2.jsx)(ErrorMessage, null, error), !errors.server ? null : (0, _react2.jsx)(ErrorMessage, null, String(errors.server)), (0, _react2.jsx)(ErrorMessage, null, errors.email || null), (0, _react2.jsx)(AuthInput, {
        type: "text",
        name: "email",
        placeholder: "Email",
        value: this.state.email,
        onChange: (0, _partial2.default)(this.handleChange, 'email')
      }), (0, _react2.jsx)(ErrorMessage, null, errors.password || null), (0, _react2.jsx)(AuthInput, {
        type: "password",
        name: "password",
        placeholder: "Password",
        value: this.state.password,
        onChange: (0, _partial2.default)(this.handleChange, 'password')
      }), (0, _react2.jsx)(LoginButton, {
        disabled: inProgress
      }, inProgress ? t('auth.loggingIn') : t('auth.login'))),
      t: t
    });
  }
}
exports.default = GitGatewayAuthenticationPage;
_defineProperty(GitGatewayAuthenticationPage, "authClient", void 0);
_defineProperty(GitGatewayAuthenticationPage, "propTypes", {
  onLogin: _propTypes.default.func.isRequired,
  inProgress: _propTypes.default.bool.isRequired,
  error: _propTypes.default.node,
  config: _propTypes.default.object.isRequired,
  t: _propTypes.default.func.isRequired
});