import { addPlaceholder, removePlaceholder } from "./droppable/with-placeholder";
import whatIsDraggedOver from "./droppable/what-is-dragged-over";
import patchDroppableMap from "./patch-droppable-map";
import isHomeOf from "./droppable/is-home-of";

const clearUnusedPlaceholder = ({ previousImpact, impact, droppables }) => {
  const last = whatIsDraggedOver(previousImpact);
  const now = whatIsDraggedOver(impact);
  if (!last) {
    return droppables;
  }

  // no change - can keep the last state
  if (last === now) {
    return droppables;
  }
  const lastDroppable = droppables[last];

  // nothing to clear
  if (!lastDroppable.subject.withPlaceholder) {
    return droppables;
  }
  const updated = removePlaceholder(lastDroppable);
  return patchDroppableMap(droppables, updated);
};

const recomputePlaceholders = ({ draggable, draggables, droppables, previousImpact, impact }) => {
  const cleaned = clearUnusedPlaceholder({
    previousImpact,
    impact,
    droppables
  });
  const isOver = whatIsDraggedOver(impact);
  if (!isOver) {
    return cleaned;
  }
  const droppable = droppables[isOver];

  // no need to add additional space to home droppable
  if (isHomeOf(draggable, droppable)) {
    return cleaned;
  }

  // already have a placeholder - nothing to do here!
  if (droppable.subject.withPlaceholder) {
    return cleaned;
  }

  // Need to patch the existing droppable
  const patched = addPlaceholder(droppable, draggable, draggables);
  return patchDroppableMap(cleaned, patched);
};

export default recomputePlaceholders;
