#!/usr/bin/env python
# -*- coding: UTF-8 -*-

import sys
sys.path.append('../..')
import logging
import os

import report
import state_machine

logger = logging.getLogger('root')
report.stdoutLoggingConfigure(log_name_lvl=[('root', 'DEBUG'), ])


class trafic_lights(state_machine.state_machine):
    LOG_PREFIX = 'TraficLights:'

    STATE_RED = 'state_red'
    STATE_GREEN = 'state_green'

    CONDITION_TRUE = 'condition_true'
    CONDITION_PEDASTRIAN_REQUEST = 'condition_pedastrian_request'

    TRANSITIONS = {
        STATE_RED: (
            (CONDITION_PEDASTRIAN_REQUEST, 1, STATE_GREEN),
        ),
        STATE_GREEN: (
            (CONDITION_TRUE, 3, STATE_RED),
        )
    }

    def condition_true(self):
        return True

    def set_padestrian_request(self):
        logger.log(self.__log_lvl__, '%s Pedestrian gave state change request.', self.LOG_PREFIX)
        self.pedastrian_request = True

    def condition_pedastrian_request(self):
        return self.pedastrian_request


sm = trafic_lights(trafic_lights.STATE_RED, logging.INFO, pedastrian_request=False)
sm.register_state_change_callback(sm.STATE_GREEN, sm.CONDITION_PEDASTRIAN_REQUEST, logger.info, 'Callback information: Traffic light had been changed to green caused by pedastrian request')
while not sm.previous_state_was(sm.STATE_GREEN):
    if sm.this_state_is(sm.STATE_RED) and sm.this_state_duration() > 0.2 and not sm.condition_pedastrian_request():
        sm.set_padestrian_request()
    sm.work()
