import memoizeOne from "memoize-one";
import { invariant } from "../../../invariant";
import isPositionInFrame from "../../visibility/is-position-in-frame";
import { toDroppableList } from "../../dimension-structures";
import { find } from "../../../native-with-fallback";

const getScrollableDroppables = memoizeOne((droppables) =>
  toDroppableList(droppables).filter((droppable) => {
    // exclude disabled droppables
    if (!droppable.isEnabled) {
      return false;
    }

    // only want droppables that are scrollable
    if (!droppable.frame) {
      return false;
    }
    return true;
  })
);
const getScrollableDroppableOver = (target, droppables) => {
  const maybe = find(getScrollableDroppables(droppables), (droppable) => {
    invariant(droppable.frame, "Invalid result");
    return isPositionInFrame(droppable.frame.pageMarginBox)(target);
  });
  return maybe;
};
const getBestScrollableDroppable = ({ center, destination, droppables }) => {
  // We need to scroll the best droppable frame we can so that the
  // placeholder buffer logic works correctly

  if (destination) {
    const dimension = droppables[destination];
    if (!dimension.frame) {
      return null;
    }
    return dimension;
  }

  // 2. If we are not over a droppable - are we over a droppable frame?
  const dimension = getScrollableDroppableOver(center, droppables);
  return dimension;
};

export default getBestScrollableDroppable;
