"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.useHasOpenLayers = useHasOpenLayers;
var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime/helpers/slicedToArray"));
var _react = require("react");
var _openLayerObserver = require("@atlaskit/layering/experimental/open-layer-observer");
var _platformFeatureFlags = require("@atlaskit/platform-feature-flags");
var _useIsFhsEnabled = require("../fhs-rollout/use-is-fhs-enabled");
/**
 * Returns whether there are any open layers across the specified namespaces, optionally filtered by type.
 */
function useHasOpenLayers(_ref) {
  var namespaces = _ref.namespaces,
    type = _ref.type;
  var isFhsEnabled = (0, _useIsFhsEnabled.useIsFhsEnabled)();
  var openLayerObserver = (0, _openLayerObserver.useOpenLayerObserver)();
  // Setting the initial state to false, as it is unlikely that there would be any open layers when the app starts.
  var _useState = (0, _react.useState)(false),
    _useState2 = (0, _slicedToArray2.default)(_useState, 2),
    hasOpenLayers = _useState2[0],
    setHasOpenLayers = _useState2[1];
  (0, _react.useEffect)(function () {
    if (!openLayerObserver || !isFhsEnabled || !(0, _platformFeatureFlags.fg)('platform-dst-side-nav-layering-fixes')) {
      return;
    }
    function updateState() {
      if (!openLayerObserver) {
        return;
      }
      var hasAnyOpenLayers = namespaces.some(function (namespace) {
        return openLayerObserver.getCount({
          namespace: namespace,
          type: type
        }) > 0;
      });
      setHasOpenLayers(hasAnyOpenLayers);
    }

    // Initial check
    updateState();

    // Subscribe to each namespace
    var cleanups = namespaces.map(function (namespace) {
      return openLayerObserver.onChange(updateState, {
        namespace: namespace
      });
    });
    return function cleanupHook() {
      cleanups.forEach(function (cleanup) {
        return cleanup();
      });
    };
  }, [isFhsEnabled, openLayerObserver, namespaces, type]);
  return hasOpenLayers;
}