import moveToNextPlace from "./move-to-next-place";
import moveCrossAxis from "./move-cross-axis";
import whatIsDraggedOver from "../droppable/what-is-dragged-over";

const getDroppableOver = (impact, droppables) => {
  const id = whatIsDraggedOver(impact);
  return id ? droppables[id] : null;
};
const moveInDirection = ({ state, type }) => {
  const isActuallyOver = getDroppableOver(state.impact, state.dimensions.droppables);
  const isMainAxisMovementAllowed = Boolean(isActuallyOver);
  const home = state.dimensions.droppables[state.critical.droppable.id];
  // use home when not actually over a droppable (can happen when move is disabled)
  const isOver = isActuallyOver || home;
  const direction = isOver.axis.direction;
  const isMovingOnMainAxis =
    (direction === "vertical" && (type === "MOVE_UP" || type === "MOVE_DOWN")) ||
    (direction === "horizontal" && (type === "MOVE_LEFT" || type === "MOVE_RIGHT"));

  // This movement is not permitted right now
  if (isMovingOnMainAxis && !isMainAxisMovementAllowed) {
    return null;
  }
  const isMovingForward = type === "MOVE_DOWN" || type === "MOVE_RIGHT";
  const draggable = state.dimensions.draggables[state.critical.draggable.id];
  const previousPageBorderBoxCenter = state.current.page.borderBoxCenter;
  const { draggables, droppables } = state.dimensions;
  return isMovingOnMainAxis
    ? moveToNextPlace({
        isMovingForward,
        previousPageBorderBoxCenter,
        draggable,
        destination: isOver,
        draggables,
        viewport: state.viewport,
        previousClientSelection: state.current.client.selection,
        previousImpact: state.impact,
        afterCritical: state.afterCritical
      })
    : moveCrossAxis({
        isMovingForward,
        previousPageBorderBoxCenter,
        draggable,
        isOver,
        draggables,
        droppables,
        viewport: state.viewport,
        afterCritical: state.afterCritical
      });
};

export default moveInDirection;
