import _asyncToGenerator from "@babel/runtime/helpers/esm/asyncToGenerator";
import _slicedToArray from "@babel/runtime/helpers/esm/slicedToArray";
import _typeof from "@babel/runtime/helpers/esm/typeof";
import _extends from "@babel/runtime/helpers/esm/extends";
import _regeneratorRuntime from "@babel/runtime/regenerator";
/* eslint-disable camelcase */
/**
 *
 * LoginSocialLinkedin
 *
 */
// import { PASS_CORS_KEY } from 'helper/constants';
/* "use client" */

import React, { memo, useCallback, useEffect } from 'react';
var LINKEDIN_URL = 'https://www.linkedin.com/oauth/v2';
var LINKEDIN_API_URL = 'https://api.linkedin.com';
var PREVENT_CORS_URL = '';
export var LoginSocialLinkedin = function LoginSocialLinkedin(_ref) {
  var _ref$state = _ref.state,
    state = _ref$state === void 0 ? '' : _ref$state,
    _ref$scope = _ref.scope,
    scope = _ref$scope === void 0 ? 'r_liteprofile' : _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$response_type = _ref.response_type,
    response_type = _ref$response_type === void 0 ? 'code' : _ref$response_type,
    _ref$isOnlyGetCode = _ref.isOnlyGetCode,
    isOnlyGetCode = _ref$isOnlyGetCode === void 0 ? false : _ref$isOnlyGetCode,
    _ref$isOnlyGetToken = _ref.isOnlyGetToken,
    isOnlyGetToken = _ref$isOnlyGetToken === void 0 ? false : _ref$isOnlyGetToken,
    children = _ref.children,
    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('_linkedin') && code) {
      localStorage.setItem('linkedin', code);
      window.close();
    }
  }, []);
  var getProfile = useCallback(function (data) {
    fetch("https://api.allorigins.win/get?url=".concat(encodeURIComponent(LINKEDIN_API_URL + '/v2/me?oauth2_access_token=' + data.access_token + '&projection=(id,profilePicture(displayImage~digitalmediaAsset:playableStreams),localizedLastName, firstName,lastName,localizedFirstName)')), {
      method: 'GET'
    }).then(function (res) {
      return res.json();
    }).then(function (res) {
      var response = _extends({}, data);
      if (res.contents) {
        var contents = JSON.parse(res.contents);
        if (_typeof(data) === 'object') Object.entries(contents).map(function (_ref2) {
          var _ref3 = _slicedToArray(_ref2, 2),
            key = _ref3[0],
            value = _ref3[1];
          response[key] = value;
        });
      }
      onResolve({
        provider: 'linkedin',
        data: response
      });
    })["catch"](function (err) {
      onReject(err);
    });
  }, [onReject, onResolve]);
  var getAccessToken = useCallback(function (code) {
    if (isOnlyGetCode) onResolve({
      provider: 'linkedin',
      data: {
        code: code
      }
    });else {
      var params = {
        code: code,
        grant_type: 'authorization_code',
        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(LINKEDIN_URL, "/accessToken"), {
        method: 'POST',
        headers: headers,
        body: new URLSearchParams(params)
      }).then(function (response) {
        return response.json();
      }).then(function (response) {
        if (isOnlyGetToken) onResolve({
          provider: 'linkedin',
          data: response
        });else getProfile(response);
      })["catch"](function (err) {
        onReject(err);
      });
    }
  }, [onReject, onResolve, client_id, getProfile, redirect_uri, client_secret, isOnlyGetCode, isOnlyGetToken]);
  var handlePostMessage = useCallback(/*#__PURE__*/function () {
    var _ref5 = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee(_ref4) {
      var type, code, provider;
      return _regeneratorRuntime.wrap(function (_context) {
        while (1) switch (_context.prev = _context.next) {
          case 0:
            type = _ref4.type, code = _ref4.code, provider = _ref4.provider;
            return _context.abrupt("return", type === 'code' && provider === 'linkedin' && code && getAccessToken(code));
          case 1:
          case "end":
            return _context.stop();
        }
      }, _callee);
    }));
    return function (_x) {
      return _ref5.apply(this, arguments);
    };
  }(), [getAccessToken]);
  var onChangeLocalStorage = useCallback(function () {
    window.removeEventListener('storage', onChangeLocalStorage, false);
    var code = localStorage.getItem('linkedin');
    if (code) {
      handlePostMessage({
        provider: 'linkedin',
        type: 'code',
        code: code
      });
      localStorage.removeItem('linkedin');
    }
  }, [handlePostMessage]);
  var onLogin = useCallback(function () {
    onLoginStart && onLoginStart();
    window.addEventListener('storage', onChangeLocalStorage, false);
    var oauthUrl = "".concat(LINKEDIN_URL, "/authorization?response_type=").concat(response_type, "&client_id=").concat(client_id, "&scope=").concat(scope, "&state=").concat(state + '_linkedin', "&redirect_uri=").concat(redirect_uri);
    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, 'Linkedin', 'menubar=no,location=no,resizable=no,scrollbars=no,status=no, width=' + width + ', height=' + height + ', top=' + top + ', left=' + left);
  }, [onLoginStart, onChangeLocalStorage, response_type, client_id, scope, state, redirect_uri]);
  return /*#__PURE__*/React.createElement("div", {
    className: className,
    onClick: onLogin
  }, children);
};
export default /*#__PURE__*/memo(LoginSocialLinkedin);