/**
  State Machine
  
  A simple Finite State Machine
  
  Create states, run registered callback based on current state, and trigger a callback when moving to a new state.
  All current state callbacks must return the next state to transition to. This cane be the same as the current state.
  
  Callbacks will have state machine user data passed in.
 */

import _ from 'underscore';

export const ERROR = 'STATEMACHINEERROR';

export const create = (states) => {
  return {
    defaultState: states[0],
    currentState: states[0],
    states,
    stateFunction: {},
    transitionFunction: {},
  };
};

export const registerStateFunction = (sm, state, func) => {
  if (!_.contains(sm.states, state)) {
    return false;
  }
  sm.stateFunction[state] = func;
  return true;
};

export const registerTransitionFunction = (sm, state, func) => {
  if (!_.contains(sm.states, state)) {
    return false;
  }
  sm.transitionFunction[state] = func;
  return true;
};

export const run = (sm, userData) => {
  if (!_.contains(sm.states, sm.currentState)) {
    return false;
  }
  if (sm.stateFunction[sm.currentState]) {
    const newState = sm.stateFunction[sm.currentState](userData);
    change(sm, newState, userData);
  }
};

export const change = (sm, newState, userData) => {
  if (newState === ERROR) {
    console.log('State machine error');
    sm.currentState = sm.defaultState;
  } else if (newState !== sm.currentState) {
    sm.currentState = newState;
    if (sm.transitionFunction[sm.currentState]) {
      sm.transitionFunction[sm.currentState](userData);
    }
  }
};

@@ -452,16 +452,23 @@
  (states
+, debug
 ) =%3E %7B%0A 
@@ -600,18 +600,258 @@
 : %7B%7D,%0A  
+  debug: debug %7C%7C false%0A  %7D;%0A%7D;%0A%0Aconst log = (sm, message) =%3E %7B%0A  if (!sm.debug) return;%0A  if (message) %7B%0A    console.log(%60State Machine - $%7Bsm.currentState%7D: $%7Bmessage%7D%60);%0A  %7D else %7B%0A    console.log(%60State Machine - $%7Bsm.currentState%7D%60);%0A  
 %7D
-;
 %0A%7D;%0A%0Aexp
@@ -1315,16 +1315,27 @@
 se;%0A  %7D%0A
+  log(sm);%0A
   if (sm
@@ -1567,40 +1567,22 @@
     
-console.log('State machine error
+log(sm, 'ERROR
 ');%0A
@@ -1661,24 +1661,55 @@
 entState) %7B%0A
+    log(sm, %60-%3E $%7BnewState%7D%60);%0A
     sm.curre

Add debug logging to state machine