/******************************************************************************
* Statemachine implementation
* ***************************************************************************/
/**
* Describes a statemachine
* @param obj {object} an object describing a state machine. If obj is empty then the statemachine is empty
* @class
*/
ARCS.Statemachine = function (obj) {
// dynamic construction: properties are initial state that have properties
// that are tokens and value that are the final state
var initial = "", final = "", transitions = {}, currentState = "";
if (obj !== undefined) {
initial = obj.initial;
final = obj.final;
transitions = obj.transitions;
currentState = "";
}
/**
* Sets the initial state of the statemachine
* @param string {string} name of the initial state
*/
this.setInitialState = function (string) {
initial = string;
currentState = initial;
};
/**
* Sets the final state of the statemachine
* @param string {string} name of the final state
*/
this.setFinalState = function (string) { final = string; };
/**
* Adds a transition to the state machine
* @param start {string} name of the state at the beginning of the transition
* @param token {string} name of the token triggering the transition
* @param end {string} name of the state reached at the end of the transition
*/
this.addTransition = function (start, token, end) {
transitions[start][token] = end;
};
/**
* Gives a token to the statemachine. According to its list of transitions
* and the current state, it may trigger a transition
* @param token {string} name of the token
*/
this.setToken = function (token) {
if (transitions[currentState] !== undefined) {
if (transitions[currentState][token] !== undefined) {
currentState = transitions[currentState][token];
this.emit('requestSheet', currentState);
if (currentState === final) {
this.emit('requestTermination');
}
}
}
};
/**
* Sets transitions from a list of transitions
* @param obj {object[]} list of transitions
*/
this.setTransitions = function (obj) { transitions = obj; };
/**
* Initialize and starts the statemachine, setting its current state to
* the initial state (by default, it is the departure of the first transition
*/
this.start = function () {
currentState = initial;
this.emit('requestSheet', currentState);
};
};
ARCS.Component.create(ARCS.Statemachine);
ARCS.Statemachine.slot("setToken");
ARCS.Statemachine.signal("requestSheet");
ARCS.Statemachine.signal("requestTermination");