package com.jscape.util.fsm;

import static com.jscape.util.Parameters.assertNotNull;

/**
 * @author Alex Usun
 */
public abstract class AbstractFSM {

    protected final StateTransitions transitions;
    protected final EventSource eventSource;
    protected final State endState;
    protected State currentState;

    protected AbstractFSM(StateTransitions transitions, EventSource eventSource, State initialState, State endState) {
        assertNotNull(transitions);
        this.transitions = transitions;

        assertNotNull(eventSource);
        this.eventSource = eventSource;

        assertNotNull(endState);
        this.endState = endState;

        assertNotNull(initialState);
        this.currentState = initialState;
    }

    protected void execute()
            throws FSMException {
        while (this.currentState != this.endState) {
            Event event = this.eventSource.nextEvent();
            this.currentState = this.transitions.stateFor(this.currentState, event);
            this.currentState.onEvent(event, this.eventSource);
        }
    }

}
