istory persistence middleware is responsible for loading
 * and maintaining history of executed expressions in JSTerm.
 */
function historyPersistenceMiddleware(store) {
  let historyLoaded = false;
  asyncStorage.getItem("webConsoleHistory").then(
    value => {
      if (Array.isArray(value)) {
        store.dispatch(historyActions.historyLoaded(value));
      }
      historyLoaded = true;
    },
    err => {
      historyLoaded = true;
      console.error(err);
    }
  );

  return next => action => {
    const res = next(action);

    const triggerStoreActions = [
      APPEND_TO_HISTORY,
      CLEAR_HISTORY,
      EVALUATE_EXPRESSION,
    ];

    // Save the current history entries when modified, but wait till
    // entries from the previous session are loaded.
    if (historyLoaded && triggerStoreActions.includes(action.type)) {
      const state = store.getState();
      asyncStorage
        .setItem("webConsoleHistory", state.history.entries)
        .catch(e => {
          console.error("Error when saving WebConsole input history", e);
        });
    }

    return res;
  };
}

module.exports = historyPersistenceMiddleware;
PK