import { moveByWindowScroll } from "../action-creators";
import getScrollListener from "../../view/scroll-listener";

// TODO: this is taken from auto-scroll. Let's make it a util
const shouldEnd = (action) =>
  action.type === "DROP_COMPLETE" || action.type === "DROP_ANIMATE" || action.type === "FLUSH";

const scrollListener = (store) => {
  const listener = getScrollListener({
    onWindowScroll: (newScroll) => {
      store.dispatch(
        moveByWindowScroll({
          newScroll
        })
      );
    }
  });
  return (next) => (action) => {
    if (!listener.isActive() && action.type === "INITIAL_PUBLISH") {
      listener.start();
    }
    if (listener.isActive() && shouldEnd(action)) {
      listener.stop();
    }
    next(action);
  };
};

export default scrollListener;
