import _asyncToGenerator from "@babel/runtime/helpers/esm/asyncToGenerator";
import _extends from "@babel/runtime/helpers/esm/extends";
import _regeneratorRuntime from "@babel/runtime/regenerator";
/* eslint-disable camelcase */
/**
 *
 * LoginSocialMicrosoft
 *
 */
/* "use client" */

import React, { memo, useCallback, useEffect } from 'react';
var MICROSOFT_URL = 'https://login.microsoftonline.com';
var MICROSOFT_API_URL = 'https://graph.microsoft.com';
// const PREVENT_CORS_URL: string = 'https://cors.bridged.cc'

export var LoginSocialMicrosoft = function LoginSocialMicrosoft(_ref) {
  var _ref$tenant = _ref.tenant,
    tenant = _ref$tenant === void 0 ? 'common' : _ref$tenant,
    _ref$state = _ref.state,
    state = _ref$state === void 0 ? '' : _ref$state,
    client_id = _ref.client_id,
    className = _ref.className,
    redirect_uri = _ref.redirect_uri,
    _ref$scope = _ref.scope,
    scope = _ref$scope === void 0 ? 'profile openid email' : _ref$scope,
    _ref$response_type = _ref.response_type,
    response_type = _ref$response_type === void 0 ? 'code' : _ref$response_type,
    _ref$response_mode = _ref.response_mode,
    response_mode = _ref$response_mode === void 0 ? 'query' : _ref$response_mode,
    children = _ref.children,
    _ref$code_challenge = _ref.code_challenge,
    code_challenge = _ref$code_challenge === void 0 ? '19cfc47c216dacba8ca23eeee817603e2ba34fe0976378662ba31688ed302fa9' : _ref$code_challenge,
    _ref$code_challenge_m = _ref.code_challenge_method,
    code_challenge_method = _ref$code_challenge_m === void 0 ? 'plain' : _ref$code_challenge_m,
    _ref$prompt = _ref.prompt,
    prompt = _ref$prompt === void 0 ? 'select_account' : _ref$prompt,
    _ref$isOnlyGetCode = _ref.isOnlyGetCode,
    isOnlyGetCode = _ref$isOnlyGetCode === void 0 ? false : _ref$isOnlyGetCode,
    _ref$isOnlyGetToken = _ref.isOnlyGetToken,
    isOnlyGetToken = _ref$isOnlyGetToken === void 0 ? false : _ref$isOnlyGetToken,
    onLoginStart = _ref.onLoginStart,
    onReject = _ref.onReject,
    onResolve = _ref.onResolve;
  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('_microsoft') && code) {
      localStorage.setItem('microsoft', code);
      window.close();
    }
  }, []);
  var getProfile = useCallback(function (data) {
    fetch("".concat(MICROSOFT_API_URL, "/v1.0/me"), {
      method: 'GET',
      headers: {
        Authorization: "Bearer ".concat(data.access_token)
      }
    }).then(function (res) {
      return res.json();
    }).then(function (res) {
      onResolve({
        provider: 'microsoft',
        data: _extends({}, res, data)
      });
    })["catch"](function (err) {
      onReject(err);
    });
  }, [onReject, onResolve]);
  var getAccessToken = useCallback(function (code) {
    if (isOnlyGetCode) onResolve({
      provider: 'microsoft',
      data: {
        code: code
      }
    });else {
      var params = {
        code: code,
        scope: scope,
        client_id: client_id,
        redirect_uri: redirect_uri,
        code_verifier: code_challenge,
        grant_type: 'authorization_code'
      };
      var headers = new Headers({
        'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
      });
      fetch("".concat(MICROSOFT_URL, "/").concat(tenant, "/oauth2/v2.0/token"), {
        method: 'POST',
        headers: headers,
        body: new URLSearchParams(params)
      }).then(function (response) {
        return response.json();
      }).then(function (data) {
        if (data.access_token) {
          if (isOnlyGetToken) onResolve({
            provider: 'microsoft',
            data: data
          });else getProfile(data);
        } else {
          onReject('no data');
        }
      })["catch"](function (err) {
        onReject(err);
      });
    }
  }, [scope, tenant, onReject, getProfile, client_id, onResolve, redirect_uri, code_challenge, 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 === 'microsoft' && 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('microsoft');
    if (code) {
      handlePostMessage({
        provider: 'microsoft',
        type: 'code',
        code: code
      });
      localStorage.removeItem('microsoft');
    }
  }, [handlePostMessage]);
  var onLogin = useCallback(function () {
    onLoginStart && onLoginStart();
    window.addEventListener('storage', onChangeLocalStorage, false);
    var oauthUrl = "".concat(MICROSOFT_URL, "/").concat(tenant, "/oauth2/v2.0/authorize?client_id=").concat(client_id, "\n        &response_type=").concat(response_type, "\n        &redirect_uri=").concat(redirect_uri, "\n        &response_mode=").concat(response_mode, "\n        &scope=").concat(scope, "\n        &state=").concat(state + '_microsoft', "\n        &prompt=").concat(prompt, "\n        &code_challenge=").concat(code_challenge, "\n        &code_challenge_method=").concat(code_challenge_method);
    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, 'Microsoft', 'menubar=no,location=no,resizable=no,scrollbars=no,status=no, width=' + width + ', height=' + height + ', top=' + top + ', left=' + left);
  }, [scope, state, prompt, tenant, client_id, onLoginStart, redirect_uri, response_mode, response_type, code_challenge, onChangeLocalStorage, code_challenge_method]);
  return /*#__PURE__*/React.createElement("div", {
    className: className,
    onClick: onLogin
  }, children);
};
export default /*#__PURE__*/memo(LoginSocialMicrosoft);