#!/usr/bin/ruby
<%
var i, j,
        outerIf = 'if',
        innerIf = 'if',
        initialStateName;

for (i = 0; i < stateMachine.states.length; i += 1) {
    if (stateMachine.states[i].id === stateMachine.initialState) {
        initialStateName = stateMachine.states[i].name;
        break;
    }
}

%>
puts "State machine for <%=stateMachine.name%>. Type 'exit' to exit the program any time."

finalStates = []
<%for (i = 0; i < stateMachine.finalStates.length; i += 1) {%>finalStates << "<%=stateMachine.finalStates[i]%>"
<%}%>

currentStateId = "<%=stateMachine.initialState%>"
currentState = "<%=initialStateName%>"

currentInput = ""
while currentInput != "exit" do
    puts "Current state: #{currentState} (#{currentStateId})"
    print "Enter an event: "
    $stdout.flush
    currentInput = gets.chomp

<%for (i = 0; i < stateMachine.states.length; i += 1) {
    var eventStr = '';
    if (stateMachine.states[i].transitions.length === 0) {
        continue;
    }
    innerIf = 'if';%>    <%=outerIf%> currentStateId == "<%=stateMachine.states[i].id%>"
<%for (j = 0; j < stateMachine.states[i].transitions.length; j += 1) {
    var transition = stateMachine.states[i].transitions[j];
    eventStr += ', ' + transition.event;
%>        <%=innerIf%> currentInput == "<%=transition.event%>"
            puts "Switching state to <%=transition.targetName%> (<%=transition.targetId%>)"
            currentStateId = "<%=transition.targetId%>"
            currentState = "<%=transition.targetName%>"
<%if (j === stateMachine.states[i].transitions.length - 1) {%>
        else
            puts "Possible events for transition(s): <%=eventStr.substring(2)%>"
        end
<%}
    innerIf = 'elsif';
}
if (i === stateMachine.states.length - 1) {%>
    end
<%}
outerIf = 'elsif';
}%>
    if finalStates.index(currentStateId) != nil
        puts "At final state #{currentState} (#{currentStateId})"
        break
    end
    
end

puts "Press enter to exit";
gets.chomp