from random import randint
from time import clock

State = type("State", (object,), {})


class LightOn(State):
    def execute():
        print("Light is on")


class LightOff(State):
    def execute():
        print("Light is off")


class Transition(object):
    def __init__(self, to_state):
        self.to_state = to_state

    def execute(self):
        print("Trasnitioning ... ")


class StateMachine(object):
    def __init__(self, char):
        self.char = char
        self.states = {}
        self.transitions = {}
        self.current_state = None
        self.current_transition = None

    def set_state(self, state_name):
        self.current_state = state_name

    def set_transition(self, transition_name):
        self.current_transition = transition_name

    def execute(self):
        if (self.current_transition):
            self.transitions[self.current_transition].execute()
            self.set_state(self.transitions[self.current_transition].to_state)
            self.current_transition = None
        self.states[self.current_state].execute()


class Character(object):
    def __init__(self):
        self.state_machine = StateMachine(self)
        self.LightOn = True


if __name__ == "__main__":
    light = Character()
    light.state_machine.states["ON"] = LightOn
    light.state_machine.states["OFF"] = LightOff
    light.state_machine.transitions["TO_ON"] = Transition("ON")
    light.state_machine.transitions["TO_OFF"] = Transition("OFF")

    light.state_machine.set_state("ON")
    for i in range(20):
        start_time = clock()
        time_interval = 1
        while (start_time + time_interval > clock()):
            pass
        if (randint(0,2)):
            if (light.LightOn):
                light.state_machine.set_transition("TO_OFF")
                light.LightOn = False
            else:
                light.state_machine.set_transition("TO_ON")
                light.LightOn = True
        light.state_machine.execute()
