import { add } from "../position";
import offsetDraggable from "./offset-draggable";
import getFrame from "../get-frame";

const adjustAdditionsForScrollChanges = ({ additions, updatedDroppables, viewport }) => {
  // We need to adjust collected draggables so that they
  // match the model we had when the drag started.
  // When a draggable is dynamically collected it does not have
  // the same relative client position. We need to unwind
  // any changes in window scroll and droppable scroll so that
  // the newly collected draggables fit in with our other draggables
  // and give the same dimensions that would have had if they were
  // collected at the start of the drag.

  // Need to undo the displacement caused by window scroll changes
  const windowScrollChange = viewport.scroll.diff.value;
  // These modified droppables have already had their scroll changes correctly updated

  return additions.map((draggable) => {
    const droppableId = draggable.descriptor.droppableId;
    const modified = updatedDroppables[droppableId];
    const frame = getFrame(modified);
    const droppableScrollChange = frame.scroll.diff.value;
    const totalChange = add(windowScrollChange, droppableScrollChange);
    const moved = offsetDraggable({
      draggable,
      offset: totalChange,
      initialWindowScroll: viewport.scroll.initial
    });
    return moved;
  });
};

export default adjustAdditionsForScrollChanges;
