import _slicedToArray from "@babel/runtime/helpers/slicedToArray";
import { useEffect, useState } from 'react';
import { useOpenLayerObserver } from '@atlaskit/layering/experimental/open-layer-observer';
import { fg } from '@atlaskit/platform-feature-flags';
import { useIsFhsEnabled } from '../fhs-rollout/use-is-fhs-enabled';

/**
 * Returns whether there are any open layers across the specified namespaces, optionally filtered by type.
 */
export function useHasOpenLayers(_ref) {
  var namespaces = _ref.namespaces,
    type = _ref.type;
  var isFhsEnabled = useIsFhsEnabled();
  var 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 = useState(false),
    _useState2 = _slicedToArray(_useState, 2),
    hasOpenLayers = _useState2[0],
    setHasOpenLayers = _useState2[1];
  useEffect(function () {
    if (!openLayerObserver || !isFhsEnabled || !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;
}