import asyncio, logging
#from transitions import Machine
import transitions


def setup_state_machine(model):
    states = ['idle', 'start', 'detection', 'isolation', 'stop']

    # triggers coming from the vehicle
    #vehicle_triggers = ['idling', 'homing', 'moving', 'at_target']

    # triggers coming from fault detection itself
    #self_triggers = ['fault_detected', 'isolation_finished', 'timer_expiration']

    # triggers that will cause detection to run:
    #detection_triggers = ['timer_expiration', 'moving']

    # trigger that will go back to detection, but not cause detection algo to run
    #no_detection_trigger = ['isolation_finished']

    #     {'trigger': , 'source': , 'dest': },
    mytransitions = [
        {'trigger': 'idling', 'source': '*', 'dest': 'idle'},
        {'trigger': 'homing', 'source': '*', 'dest': 'idle'},
        {'trigger': 'moving', 'source': 'idle', 'dest': 'start'},
        {'trigger': 'moving', 'source': 'start', 'dest': None}, 
        {'trigger': 'moving', 'source': 'detection', 'dest': None, 'after': model.detection_algorithm},
        {'trigger': 'at_target', 'source': ['start','detection', 'isolation'], 'dest':'stop'},
        {'trigger': 'at_target', 'source': ['stop', 'idle'], 'dest': None},
        {'trigger': 'timer_expiration', 'source': 'start', 'dest': 'detection', 'after': model.detection_algorithm},
        {'trigger': 'moving', 'source': 'stop', 'dest': None},
        {'trigger': 'timer_expiration', 'source': 'stop', 'dest': 'idle'},
        {'trigger': 'fault_detected', 'source': 'detection', 'dest':'isolation'},
        {'trigger': 'isolation_finished', 'source': 'isolation', 'dest': 'detection'}, # don't run detection
    ]

    transitions.core._LOGGER.setLevel(logging.WARN)
    return transitions.Machine(model=model, states=states, initial='idle', transitions=mytransitions)
