import parseJSON from '../utils/parseJSON';

function recompute(previousLiftedState, storeState, action, nextActionId) {
  const actionId = nextActionId - 1;
  const liftedState = { ...previousLiftedState };
  liftedState.stagedActionIds = [...liftedState.stagedActionIds, actionId];
  liftedState.actionsById = { ...liftedState.actionsById };
  liftedState.actionsById[actionId] = action;
  liftedState.nextActionId = nextActionId;
  liftedState.computedStates = [...liftedState.computedStates, { state: storeState }];
  liftedState.currentStateIndex++;
  return liftedState;
}

export default function updateState(store, request) {
  const payload = parseJSON(request.payload);
  if (!payload) return null;

  switch (request.type) {
    case 'ACTION':
      const newState = recompute(store.liftedStore.getState(), payload, parseJSON(request.action), request.nextActionId);
      store.liftedStore.setState(newState);
      return newState;
    case 'STATE':
      store.liftedStore.setState(payload);
      return payload;
    default:
      return null;
  }
}

@@ -110,16 +110,20 @@
 ActionId
+ = 1
 ) %7B%0A  co
@@ -347,51 +347,262 @@
 ;%0A  
-liftedState.actionsById%5BactionId%5D = action;
+if (action.type === 'PERFORM_ACTION') %7B%0A    liftedState.actionsById%5BactionId%5D = action;%0A  %7D else %7B%0A    liftedState.actionsById%5BactionId%5D = %7B%0A      action: action.action %7C%7C action,%0A      timestamp: action.timestamp,%0A      type: 'PERFORM_ACTION'%0A    %7D;%0A  %7D
 %0A  l
@@ -918,16 +918,116 @@
  null;%0A%0A
+  let newState;%0A  let action = %7B%7D;%0A  if (request.action) action = parseJSON(request.action) %7C%7C %7B%7D;%0A%0A
   switch
@@ -1058,22 +1058,20 @@
 se '
-ACTION
+INIT
 ':%0A     
  con
@@ -1066,22 +1066,16 @@
 ':%0A     
- 
-const
  newStat
@@ -1088,16 +1088,25 @@
 compute(
+%0A        
 store.li
@@ -1122,16 +1122,23 @@
 .get
+Initial
 State(),
  pay
@@ -1133,16 +1133,24 @@
 State(),
+%0A       
  payload
@@ -1154,59 +1154,148 @@
 oad,
- parseJSON(request.action), request.nextActionId);%0A
+%0A        %7B action: %7B type: '@@INIT' %7D, timestamp: action.timestamp %7D%0A      );%0A      break;%0A    case 'ACTION':%0A      newState = recompute(%0A  
     
@@ -1314,25 +1314,25 @@
 edStore.
-s
+g
 etState(
 newState
@@ -1327,40 +1327,93 @@
 ate(
-newState);%0A
+),%0A        payload,%0A        action,%0A 
       
+ 
 re
-turn newState
+quest.nextActionId%0A      );%0A      break
 ;%0A  
@@ -1438,51 +1438,34 @@
     
-store.liftedStore.set
+new
 State
-(
+ = 
 payload
-)
 ;%0A      
 retu
@@ -1464,22 +1464,13 @@
     
+b
 re
-turn payload
+ak
 ;%0A  
@@ -1503,10 +1503,69 @@
 ll;%0A  %7D%0A
+  store.liftedStore.setState(newState);%0A  return newState;%0A
 %7D%0A

Create `INIT` action