import _asyncToGenerator from "@babel/runtime/helpers/asyncToGenerator";

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

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

/* eslint-disable @typescript-eslint/camelcase */
import React, { useEffect } from 'react';
import { useScript } from './useScript';
import { useGlobalLabels } from '@sentecacommerce-theme/lib';
import { Button, IconAppleLogin } from '../../../../../..';

var generateQueryString = q => {
  var queryString = '';

  if (q) {
    var queryKeys = Object.keys(q);
    queryKeys.forEach(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;
};

export var AppleLogin = props => {
  var _props$designProp;

  var {
    clientId,
    redirectURI,
    state = '',
    render,
    responseMode = 'query',
    responseType = 'code',
    nonce,
    callback,
    scope,
    autoLoad = false,
    usePopup = false
  } = props;
  var {
    buttons
  } = useGlobalLabels();
  var [loaded] = 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");

  var onClick = /*#__PURE__*/function () {
    var _ref = _asyncToGenerator(function* (e) {
      if (e === void 0) {
        e = null;
      }

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

      if (!usePopup) {
        window.location.href = "https://appleid.apple.com/auth/authorize?" + generateQueryString({
          response_type: responseType,
          response_mode: responseMode,
          client_id: clientId,
          redirect_uri: encodeURIComponent(redirectURI),
          state,
          nonce,
          scope: responseMode === 'query' ? '' : scope
        });
      } else {
        try {
          var data = yield AppleID.auth.signIn();

          if (typeof callback === 'function' && data) {
            callback(data);
          }
        } catch (err) {
          if (typeof callback === 'function') {
            callback({
              error: err
            });
          }
        }
      }
    });

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

  useEffect(() => {
    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 = 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 () => {};
  }, []);
  useEffect(() => {
    if (usePopup && loaded) {
      AppleID.auth.init({
        clientId,
        scope,
        redirectURI: redirectURI || location.protocol + "//" + location.host + location.pathname,
        state,
        nonce,
        usePopup
      }); // Call on auto load.

      if (autoLoad) {
        onClick();
      }
    }

    return () => {};
  }, [loaded, usePopup]);

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

  return /*#__PURE__*/React.createElement(Button, {
    bordered: true,
    fullWidth: true,
    type: "button",
    icon: /*#__PURE__*/React.createElement(IconAppleLogin, null),
    iconPosition: "left",
    onClick: onClick
  }, buttons.appleLogin);
};
//# sourceMappingURL=index.js.map