import { invariant } from "../../invariant";

const shouldStop = (action) =>
  action.type === "DROP_COMPLETE" || action.type === "DROP_ANIMATE" || action.type === "FLUSH";

const autoScroll = (autoScroller) => (store) => (next) => (action) => {
  if (shouldStop(action)) {
    autoScroller.stop();
    next(action);
    return;
  }
  if (action.type === "INITIAL_PUBLISH") {
    // letting the action go first to hydrate the state
    next(action);
    const state = store.getState();
    invariant(state.phase === "DRAGGING", "Expected phase to be DRAGGING after INITIAL_PUBLISH");
    autoScroller.start(state);
    return;
  }

  // auto scroll happens in response to state changes
  // releasing all actions to the reducer first
  next(action);
  autoScroller.scroll(store.getState());
};

export default autoScroll;
