import _slicedToArray from "@babel/runtime/helpers/esm/slicedToArray";
import _toConsumableArray from "@babel/runtime/helpers/esm/toConsumableArray";
import * as React from 'react';
import { pathKey } from "../Cache";
import StyleContext from "../StyleContext";
import useCompatibleInsertionEffect from "./useCompatibleInsertionEffect";
import useEffectCleanupRegister from "./useEffectCleanupRegister";
import useHMR from "./useHMR";
export default function useGlobalCache(prefix, keyPath, cacheFn, onCacheRemove,
// Add additional effect trigger by `useInsertionEffect`
onCacheEffect) {
  var _React$useContext = React.useContext(StyleContext),
    globalCache = _React$useContext.cache;
  var fullPath = [prefix].concat(_toConsumableArray(keyPath));
  var fullPathStr = pathKey(fullPath);
  var register = useEffectCleanupRegister([fullPathStr]);
  var HMRUpdate = useHMR();
  var buildCache = function buildCache(updater) {
    globalCache.opUpdate(fullPathStr, function (prevCache) {
      var _ref = prevCache || [undefined, undefined],
        _ref2 = _slicedToArray(_ref, 2),
        _ref2$ = _ref2[0],
        times = _ref2$ === void 0 ? 0 : _ref2$,
        cache = _ref2[1];

      // HMR should always ignore cache since developer may change it
      var tmpCache = cache;
      if (process.env.NODE_ENV !== 'production' && cache && HMRUpdate) {
        onCacheRemove === null || onCacheRemove === void 0 || onCacheRemove(tmpCache, HMRUpdate);
        tmpCache = null;
      }
      var mergedCache = tmpCache || cacheFn();
      var data = [times, mergedCache];

      // Call updater if need additional logic
      return updater ? updater(data) : data;
    });
  };

  // Create cache
  React.useMemo(function () {
    buildCache();
  }, /* eslint-disable react-hooks/exhaustive-deps */
  [fullPathStr]
  /* eslint-enable */);
  var cacheEntity = globalCache.opGet(fullPathStr);

  // HMR clean the cache but not trigger `useMemo` again
  // Let's fallback of this
  // ref https://github.com/ant-design/cssinjs/issues/127
  if (process.env.NODE_ENV !== 'production' && !cacheEntity) {
    buildCache();
    cacheEntity = globalCache.opGet(fullPathStr);
  }
  var cacheContent = cacheEntity[1];

  // Remove if no need anymore
  useCompatibleInsertionEffect(function () {
    onCacheEffect === null || onCacheEffect === void 0 || onCacheEffect(cacheContent);
  }, function (polyfill) {
    // It's bad to call build again in effect.
    // But we have to do this since StrictMode will call effect twice
    // which will clear cache on the first time.
    buildCache(function (_ref3) {
      var _ref4 = _slicedToArray(_ref3, 2),
        times = _ref4[0],
        cache = _ref4[1];
      if (polyfill && times === 0) {
        onCacheEffect === null || onCacheEffect === void 0 || onCacheEffect(cacheContent);
      }
      return [times + 1, cache];
    });
    return function () {
      globalCache.opUpdate(fullPathStr, function (prevCache) {
        var _ref5 = prevCache || [],
          _ref6 = _slicedToArray(_ref5, 2),
          _ref6$ = _ref6[0],
          times = _ref6$ === void 0 ? 0 : _ref6$,
          cache = _ref6[1];
        var nextCount = times - 1;
        if (nextCount === 0) {
          // Always remove styles in useEffect callback
          register(function () {
            // With polyfill, registered callback will always be called synchronously
            // But without polyfill, it will be called in effect clean up,
            // And by that time this cache is cleaned up.
            if (polyfill || !globalCache.opGet(fullPathStr)) {
              onCacheRemove === null || onCacheRemove === void 0 || onCacheRemove(cache, false);
            }
          });
          return null;
        }
        return [times - 1, cache];
      });
    };
  }, [fullPathStr]);
  return cacheContent;
}