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 */
/**
 *
 * LoginSocialPinterest
 *
 */
// import { PASS_CORS_KEY } from 'helper/constants';
/* "use client" */

import React, { memo, useCallback, useEffect } from 'react';
import { get } from 'lodash';
var PINTEREST_URL = 'https://www.pinterest.com/oauth';
var PINTEREST_URL_API = 'https://api.pinterest.com/v5';
var PREVENT_CORS_URL = '';
export var LoginSocialPinterest = function LoginSocialPinterest(_ref) {
  var _ref$state = _ref.state,
    state = _ref$state === void 0 ? '' : _ref$state,
    _ref$scope = _ref.scope,
    scope = _ref$scope === void 0 ? 'boards:read,pins:read,user_accounts:read' : _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$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('_pinterest') && code) {
      localStorage.setItem('pinterest', code);
      window.close();
    }
  }, []);
  var getProfile = useCallback(function (data) {
    fetch("".concat(PREVENT_CORS_URL, "/").concat(PINTEREST_URL_API, "/user_account"), {
      method: 'GET',
      headers: {
        Authorization: "Bearer ".concat(data.access_token)
        // 'x-cors-grida-api-key': PASS_CORS_KEY,
      }
    }).then(function (res) {
      return res.json();
    }).then(function (res) {
      onResolve({
        provider: 'pinterest',
        data: _extends({}, data, res)
      });
    })["catch"](function (err) {
      return onReject(err);
    });
  }, [onReject, onResolve]);
  var getAccessToken = useCallback(/*#__PURE__*/function () {
    var _ref2 = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee(code) {
      var details, formBody, property, encodedKey, encodedValue, data;
      return _regeneratorRuntime.wrap(function (_context) {
        while (1) switch (_context.prev = _context.next) {
          case 0:
            if (!isOnlyGetCode) {
              _context.next = 1;
              break;
            }
            onResolve({
              provider: 'pinterest',
              data: {
                code: code
              }
            });
            _context.next = 3;
            break;
          case 1:
            details = {
              code: code,
              redirect_uri: redirect_uri,
              grant_type: "authorization_code"
            };
            formBody = [];
            for (property in details) {
              encodedKey = encodeURIComponent(property);
              encodedValue = encodeURIComponent(get(details, property));
              formBody.push(encodedKey + '=' + encodedValue);
            }
            formBody = formBody.join('&');
            _context.next = 2;
            return fetch("".concat(PREVENT_CORS_URL, "/").concat(PINTEREST_URL_API, "/oauth/token"), {
              method: 'POST',
              headers: {
                Authorization: "Basic ".concat(btoa(client_id + ':' + client_secret)),
                'Content-Type': 'application/x-www-form-urlencoded'
                // 'x-cors-grida-api-key': PASS_CORS_KEY,
              },
              body: formBody
            }).then(function (data) {
              return data.json();
            })["catch"](function (err) {
              return onReject(err);
            });
          case 2:
            data = _context.sent;
            if (data.access_token) {
              if (isOnlyGetToken) onResolve({
                provider: 'pinterest',
                data: data
              });else getProfile(data);
            }
          case 3:
          case "end":
            return _context.stop();
        }
      }, _callee);
    }));
    return function (_x) {
      return _ref2.apply(this, arguments);
    };
  }(), [onReject, client_id, getProfile, onResolve, redirect_uri, client_secret, isOnlyGetCode, isOnlyGetToken]);
  var handlePostMessage = useCallback(/*#__PURE__*/function () {
    var _ref4 = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee2(_ref3) {
      var type, code, provider;
      return _regeneratorRuntime.wrap(function (_context2) {
        while (1) switch (_context2.prev = _context2.next) {
          case 0:
            type = _ref3.type, code = _ref3.code, provider = _ref3.provider;
            return _context2.abrupt("return", type === 'code' && provider === 'pinterest' && code && getAccessToken(code));
          case 1:
          case "end":
            return _context2.stop();
        }
      }, _callee2);
    }));
    return function (_x2) {
      return _ref4.apply(this, arguments);
    };
  }(), [getAccessToken]);
  var onChangeLocalStorage = useCallback(function () {
    window.removeEventListener('storage', onChangeLocalStorage, false);
    var code = localStorage.getItem('pinterest');
    if (code) {
      handlePostMessage({
        provider: 'pinterest',
        type: 'code',
        code: code
      });
      localStorage.removeItem('pinterest');
    }
  }, [handlePostMessage]);
  var onLogin = useCallback(function () {
    onLoginStart && onLoginStart();
    window.addEventListener('storage', onChangeLocalStorage, false);
    var oauthUrl = "".concat(PINTEREST_URL, "/?client_id=").concat(client_id, "&scope=").concat(scope, "&state=").concat(state + '_pinterest', "&redirect_uri=").concat(redirect_uri, "&response_type=code");
    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, 'Pinterest', 'menubar=no,location=no,resizable=no,scrollbars=no,status=no, width=' + width + ', height=' + height + ', top=' + top + ', left=' + left);
  }, [scope, state, client_id, redirect_uri, onLoginStart, onChangeLocalStorage]);
  return /*#__PURE__*/React.createElement("div", {
    className: className,
    onClick: onLogin
  }, children);
};
export default /*#__PURE__*/memo(LoginSocialPinterest);