"use strict";

exports.__esModule = true;
exports.useCollectionReachBottom = useCollectionReachBottom;
var _react = require("react");
var _CollectionReachBottom = require("../state/CollectionReachBottom");
var _react2 = require("@wix/bex-core/react");
var _util = require("@wix/bex-core/util");
function useCollectionReachBottom({
  collection,
  containerRef,
  scrollMoreAlways
}) {
  const targetRef = (0, _react.useRef)(null);
  const {
    lodash
  } = (0, _react2.useWixPatternsContainer)();
  const {
    result: {
      keyedItems
    }
  } = collection;
  const [collectionReachBottom] = (0, _react.useState)(() => new _CollectionReachBottom.CollectionReachBottom({
    collection,
    lodash
  }));
  (0, _react.useEffect)(() => {
    if ((containerRef == null ? void 0 : containerRef.current) == null) {
      return;
    }
    collectionReachBottom.reachBottom.container = containerRef == null ? void 0 : containerRef.current;
    collectionReachBottom.reachBottom.target = targetRef == null ? void 0 : targetRef.current;
    const disposers = [(0, _util.addEventListener)(collection.emitter, 'triggerReachBottomListener', () => {
      collectionReachBottom.triggerListenerIfReached();
    })];
    collectionReachBottom.subscribe();
    return () => {
      collectionReachBottom.reachBottom.target = null;
      disposers.forEach(d => d());
      collectionReachBottom.unsubscribe();
    };
  }, []);

  // Check if should load more items (scrollable container is not filled yet) after new data has been rendered
  (0, _react.useEffect)(() => {
    var _containerRef$current;
    // In jsdom element dimensions are always 0, so calculations inside `CollectionReachBottom` are not relevant.
    if (process.env.NODE_ENV === 'test') {
      return;
    }
    if (scrollMoreAlways || containerRef != null && (_containerRef$current = containerRef.current) != null && _containerRef$current.scrollHeight) {
      collectionReachBottom.triggerListenerIfReached();
    }
  }, [keyedItems.length]);
  return {
    containerRef,
    targetRef
  };
}
//# sourceMappingURL=useCollectionReachBottom.js.map