const focus = (marshal) => {
  let isWatching = false;
  return () => (next) => (action) => {
    if (action.type === "INITIAL_PUBLISH") {
      isWatching = true;
      marshal.tryRecordFocus(action.payload.critical.draggable.id);
      next(action);
      marshal.tryRestoreFocusRecorded();
      return;
    }
    next(action);
    if (!isWatching) {
      return;
    }
    if (action.type === "FLUSH") {
      isWatching = false;
      marshal.tryRestoreFocusRecorded();
      return;
    }
    if (action.type === "DROP_COMPLETE") {
      isWatching = false;
      const result = action.payload.completed.result;

      // give focus to the combine target when combining
      if (result.combine) {
        marshal.tryShiftRecord(result.draggableId, result.combine.draggableId);
      }
      marshal.tryRestoreFocusRecorded();
    }
  };
};

export default focus;
