from __future__ import absolute_import
from __future__ import print_function

import os
import sys
import optparse
import subprocess
import random

try:
    sys.path.append(os.path.join(os.path.dirname(
        __file__), '..', '..', '..', '..', "tools"))  # tutorial in tests
    sys.path.append(os.path.join(os.environ.get("SUMO_HOME", os.path.join(
        os.path.dirname(__file__), "..", "..", "..")), "tools"))  # tutorial in docs
    from sumolib import checkBinary
except ImportError:
    sys.exit(
        "please declare environment variable 'SUMO_HOME' as the root directory of your sumo installation (it should contain folders 'bin', 'tools' and 'docs')")

import traci
PORT = 8873

def run():
    traci.init(PORT)
    step = 0
    

    traci.trafficlights.setPhase("6", 0)
    traci.trafficlights.setPhase("7", 0)

    while step <= 950:
        traci.simulationStep()
        if (traci.lane.getLastStepOccupancy("1i_0") > 0.03) or (traci.lane.getLastStepOccupancy("2o_0") > 0.03):
            if traci.trafficlights.getPhase("6") == 0:
			traci.trafficlights.setPhase("6",1)
                print('Before: '+str(traci.trafficlights.getPhase("6")+' duration: '+str(traci.trafficlights.getPhaseDuration("6")))
			traci.trafficlights.setPhaseDuration("6",6)
                print('After: '+str(traci.trafficlights.getPhase("6")+' duration: '+str(traci.trafficlights.getPhaseDuration("6")))
        elif (traci.lane.getLastStepOccupancy("4i_0") > 0.03) or (traci.lane.getLastStepOccupancy("6o_0") > 0.03):
            if traci.trafficlights.getPhase("6") == 4:
                traci.trafficlights.setPhase("6",5)
        elif ((traci.lane.getLastStepOccupancy("1i_0") > 0.03) or (traci.lane.getLastStepOccupancy("2o_0") > 0.03)) and ((traci.lane.getLastStepOccupancy("6o_0") > 0.03) or (traci.lane.getLastStepOccupancy("4i_0") > 0.03)):
            if (traci.trafficlights.getPhase("6") == 3):
                traci.trafficlights.setPhase("6",4)
            elif (traci.trafficlights.getPhase("6") == 7):
                traci.trafficlights.setPhase("6",0)
        
        if (traci.lane.getLastStepOccupancy("2i_0") > 0.03) or (traci.lane.getLastStepOccupancy("3o_0") > 0.03):
            if traci.trafficlights.getPhase("7") == 0:
                traci.trafficlights.setPhase("7",1)
        elif (traci.lane.getLastStepOccupancy("5i_0") > 0.03) or (traci.lane.getLastStepOccupancy("7o_0") > 0.03):
            if traci.trafficlights.getPhase("7") == 4:
                traci.trafficlights.setPhase("7",5)
        elif ((traci.lane.getLastStepOccupancy("2i_0") > 0.03) or (traci.lane.getLastStepOccupancy("3o_0") > 0.03)) and ((traci.lane.getLastStepOccupancy("7o_0") > 0.03) or (traci.lane.getLastStepOccupancy("5i_0") > 0.03)):
            if (traci.trafficlights.getPhase("7") == 3):
                traci.trafficlights.setPhase("7",4)
            elif (traci.trafficlights.getPhase("7") == 7):
                traci.trafficlights.setPhase("7",0)        
        step += 1

    traci.close()
    sys.stdout.flush()


def get_options():
    optParser = optparse.OptionParser()
    optParser.add_option("--nogui", action="store_true",
                         default=False, help="run the commandline version of sumo")
    options, args = optParser.parse_args()
    return options


if __name__ == "__main__":
    options = get_options()

    if options.nogui:
        sumoBinary = checkBinary('sumo')
    else:
        sumoBinary = checkBinary('sumo-gui')

    sumoProcess = subprocess.Popen([sumoBinary, "-c", "data/crossteste.sumocfg", "--tripinfo-output",
                                    "tripinfo.xml", "--remote-port", str(PORT)], stdout=sys.stdout, stderr=sys.stderr)
    run()
    sumoProcess.wait()


