import _asyncToGenerator from "@babel/runtime/helpers/esm/asyncToGenerator";
import _extends from "@babel/runtime/helpers/esm/extends";
import _regeneratorRuntime from "@babel/runtime/regenerator";
function _createForOfIteratorHelper(r, e) { var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (!t) { if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e && r && "number" == typeof r.length) { t && (r = t); var _n = 0, F = function F() {}; return { s: F, n: function n() { return _n >= r.length ? { done: !0 } : { done: !1, value: r[_n++] }; }, e: function e(r) { throw r; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var o, a = !0, u = !1; return { s: function s() { t = t.call(r); }, n: function n() { var r = t.next(); return a = r.done, r; }, e: function e(r) { u = !0, o = r; }, f: function f() { try { a || null == t["return"] || t["return"](); } finally { if (u) throw o; } } }; }
function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }
function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }
/* eslint-disable camelcase */
/**
 *
 * LoginSocialGithub
 *
 */
// import { PASS_CORS_KEY } from '../helper/constants';
/* "use client" */

import React, { memo, useCallback, useEffect } from 'react';
var GITHUB_URL = 'https://github.com';
var GITHUB_API_URL = 'https://api.github.com/';
var PREVENT_CORS_URL = ''; //https://cors.bridged.cc

export var LoginSocialGithub = function LoginSocialGithub(_ref) {
  var _ref$state = _ref.state,
    state = _ref$state === void 0 ? '' : _ref$state,
    _ref$scope = _ref.scope,
    scope = _ref$scope === void 0 ? 'repo,gist' : _ref$scope,
    client_id = _ref.client_id,
    client_secret = _ref.client_secret,
    _ref$className = _ref.className,
    className = _ref$className === void 0 ? '' : _ref$className,
    redirect_uri = _ref.redirect_uri,
    _ref$allow_signup = _ref.allow_signup,
    allow_signup = _ref$allow_signup === void 0 ? false : _ref$allow_signup,
    _ref$isOnlyGetToken = _ref.isOnlyGetToken,
    isOnlyGetToken = _ref$isOnlyGetToken === void 0 ? false : _ref$isOnlyGetToken,
    _ref$isOnlyGetCode = _ref.isOnlyGetCode,
    isOnlyGetCode = _ref$isOnlyGetCode === void 0 ? false : _ref$isOnlyGetCode,
    children = _ref.children,
    onReject = _ref.onReject,
    onResolve = _ref.onResolve,
    onLoginStart = _ref.onLoginStart;
  useEffect(function () {
    var popupWindowURL = new URL(window.location.href);
    var code = popupWindowURL.searchParams.get('code');
    var state = popupWindowURL.searchParams.get('state');
    if (state !== null && state !== void 0 && state.includes('_github') && code) {
      localStorage.setItem('github', code);
      window.close();
    }
  }, []);
  var getProfile = useCallback(function (data) {
    fetch("".concat(PREVENT_CORS_URL, "/").concat(GITHUB_API_URL, "/user"), {
      method: 'GET',
      headers: {
        Authorization: "token ".concat(data.access_token)
        // 'x-cors-grida-api-key': PASS_CORS_KEY,
      }
    }).then(function (res) {
      return res.json();
    }).then(function (response) {
      onResolve({
        provider: 'github',
        data: _extends({}, response, data)
      });
    })["catch"](function (err) {
      onReject(err);
    });
  }, [onReject, onResolve]);
  var getAccessToken = useCallback(function (code) {
    if (isOnlyGetCode) onResolve({
      provider: 'github',
      data: {
        code: code
      }
    });else {
      var params = {
        code: code,
        state: state,
        redirect_uri: redirect_uri,
        client_id: client_id,
        client_secret: client_secret
      };
      var headers = new Headers({
        'Content-Type': 'application/x-www-form-urlencoded'
        // 'x-cors-grida-api-key': PASS_CORS_KEY,
      });
      fetch("".concat(PREVENT_CORS_URL, "/").concat(GITHUB_URL, "/login/oauth/access_token"), {
        method: 'POST',
        headers: headers,
        body: new URLSearchParams(params)
      }).then(function (response) {
        return response.text();
      }).then(function (response) {
        var data = {};
        var searchParams = new URLSearchParams(response);
        var _iterator = _createForOfIteratorHelper(searchParams),
          _step;
        try {
          for (_iterator.s(); !(_step = _iterator.n()).done;) {
            var p = _step.value;
            data[p[0]] = p[1];
          }
        } catch (err) {
          _iterator.e(err);
        } finally {
          _iterator.f();
        }
        if (data.access_token) {
          if (isOnlyGetToken) onResolve({
            provider: 'github',
            data: data
          });else getProfile(data);
        } else onReject('no data');
      })["catch"](function (err) {
        onReject(err);
      });
    }
  }, [state, onReject, getProfile, onResolve, client_id, redirect_uri, client_secret, isOnlyGetCode, isOnlyGetToken]);
  var handlePostMessage = useCallback(/*#__PURE__*/function () {
    var _ref3 = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee(_ref2) {
      var type, code, provider;
      return _regeneratorRuntime.wrap(function (_context) {
        while (1) switch (_context.prev = _context.next) {
          case 0:
            type = _ref2.type, code = _ref2.code, provider = _ref2.provider;
            return _context.abrupt("return", type === 'code' && provider === 'github' && code && getAccessToken(code));
          case 1:
          case "end":
            return _context.stop();
        }
      }, _callee);
    }));
    return function (_x) {
      return _ref3.apply(this, arguments);
    };
  }(), [getAccessToken]);
  var onChangeLocalStorage = useCallback(function () {
    window.removeEventListener('storage', onChangeLocalStorage, false);
    var code = localStorage.getItem('github');
    if (code) {
      handlePostMessage({
        provider: 'github',
        type: 'code',
        code: code
      });
      localStorage.removeItem('github');
    }
  }, [handlePostMessage]);
  var onLogin = useCallback(function () {
    onLoginStart && onLoginStart();
    window.addEventListener('storage', onChangeLocalStorage, false);
    var oauthUrl = "".concat(GITHUB_URL, "/login/oauth/authorize?client_id=").concat(client_id, "&scope=").concat(scope, "&state=").concat(state + '_github', "&redirect_uri=").concat(redirect_uri, "&allow_signup=").concat(allow_signup);
    var width = 450;
    var height = 730;
    var left = window.screen.width / 2 - width / 2;
    var top = window.screen.height / 2 - height / 2;
    window.open(oauthUrl, 'Github', 'menubar=no,location=no,resizable=no,scrollbars=no,status=no, width=' + width + ', height=' + height + ', top=' + top + ', left=' + left);
  }, [scope, state, client_id, redirect_uri, allow_signup, onLoginStart, onChangeLocalStorage]);
  return /*#__PURE__*/React.createElement("div", {
    className: className,
    onClick: onLogin
  }, children);
};
export default /*#__PURE__*/memo(LoginSocialGithub);