"use strict";

var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard");

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");

exports.__esModule = true;
exports.AppleLogin = void 0;

var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator"));

var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator"));

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

var _useScript2 = require("./useScript");

var _lib = require("@sentecacommerce-theme/lib");

var _ = require("../../../../../..");

/* eslint-disable react-hooks/exhaustive-deps */

/* eslint-disable no-restricted-globals */

/* eslint-disable @typescript-eslint/camelcase */
var generateQueryString = function generateQueryString(q) {
  var queryString = '';

  if (q) {
    var queryKeys = Object.keys(q);
    queryKeys.forEach(function (key) {
      if (q[key]) {
        if (q[key].toString().length) {
          queryString += key + "=" + q[key] + "&";
        }
      }
    });

    if (queryKeys.length > 0 && queryString[queryString.length - 1] === '&') {
      queryString = queryString.slice(0, -1);
    }
  }

  return queryString;
};

var AppleLogin = function AppleLogin(props) {
  var _props$designProp;

  var clientId = props.clientId,
      redirectURI = props.redirectURI,
      _props$state = props.state,
      state = _props$state === void 0 ? '' : _props$state,
      render = props.render,
      _props$responseMode = props.responseMode,
      responseMode = _props$responseMode === void 0 ? 'query' : _props$responseMode,
      _props$responseType = props.responseType,
      responseType = _props$responseType === void 0 ? 'code' : _props$responseType,
      nonce = props.nonce,
      callback = props.callback,
      scope = props.scope,
      _props$autoLoad = props.autoLoad,
      autoLoad = _props$autoLoad === void 0 ? false : _props$autoLoad,
      _props$usePopup = props.usePopup,
      usePopup = _props$usePopup === void 0 ? false : _props$usePopup;

  var _useGlobalLabels = (0, _lib.useGlobalLabels)(),
      buttons = _useGlobalLabels.buttons;

  var _useScript = (0, _useScript2.useScript)("https://appleid.cdn-apple.com/appleauth/static/jsapi/appleid/1/" + ((props == null ? void 0 : (_props$designProp = props.designProp) == null ? void 0 : _props$designProp.locale) || 'en_US') + "/appleid.auth.js"),
      loaded = _useScript[0];

  var onClick = /*#__PURE__*/function () {
    var _ref = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(e) {
      var data;
      return _regenerator["default"].wrap(function _callee$(_context) {
        while (1) {
          switch (_context.prev = _context.next) {
            case 0:
              if (e === void 0) {
                e = null;
              }

              if (e) {
                e.preventDefault();
              }

              if (usePopup) {
                _context.next = 6;
                break;
              }

              window.location.href = "https://appleid.apple.com/auth/authorize?" + generateQueryString({
                response_type: responseType,
                response_mode: responseMode,
                client_id: clientId,
                redirect_uri: encodeURIComponent(redirectURI),
                state: state,
                nonce: nonce,
                scope: responseMode === 'query' ? '' : scope
              });
              _context.next = 16;
              break;

            case 6:
              _context.prev = 6;
              _context.next = 9;
              return AppleID.auth.signIn();

            case 9:
              data = _context.sent;

              if (typeof callback === 'function' && data) {
                callback(data);
              }

              _context.next = 16;
              break;

            case 13:
              _context.prev = 13;
              _context.t0 = _context["catch"](6);

              if (typeof callback === 'function') {
                callback({
                  error: _context.t0
                });
              }

            case 16:
            case "end":
              return _context.stop();
          }
        }
      }, _callee, null, [[6, 13]]);
    }));

    return function onClick(_x) {
      return _ref.apply(this, arguments);
    };
  }();

  (0, _react.useEffect)(function () {
    if (!usePopup) {
      if (autoLoad) {
        onClick();
      }

      if (typeof callback === 'function' && responseMode === 'query' && responseType === 'code' && window && window.location) {
        var match;

        var pl = /\+/g,
            // Regex for replacing addition symbol with a space
        search = /([^&=]+)=?([^&]*)/g,
            decode = function decode(s) {
          return decodeURIComponent(s.replace(pl, ' '));
        },
            query = window.location.search.substring(1);

        var urlParams = {};

        while (match = search.exec(query)) {
          urlParams[decode(match[1])] = decode(match[2]);
        }

        if (urlParams['code']) {
          callback({
            code: urlParams['code']
          });
        }
      }
    }

    return function () {};
  }, []);
  (0, _react.useEffect)(function () {
    if (usePopup && loaded) {
      AppleID.auth.init({
        clientId: clientId,
        scope: scope,
        redirectURI: redirectURI || location.protocol + "//" + location.host + location.pathname,
        state: state,
        nonce: nonce,
        usePopup: usePopup
      }); // Call on auto load.

      if (autoLoad) {
        onClick();
      }
    }

    return function () {};
  }, [loaded, usePopup]);

  if (typeof render === 'function') {
    return render({
      onClick: onClick
    });
  }

  return /*#__PURE__*/_react["default"].createElement(_.Button, {
    bordered: true,
    fullWidth: true,
    type: "button",
    icon: /*#__PURE__*/_react["default"].createElement(_.IconAppleLogin, null),
    iconPosition: "left",
    onClick: onClick
  }, buttons.appleLogin);
};

exports.AppleLogin = AppleLogin;
//# sourceMappingURL=index.js.map