import os
import sys, gc
import optparse
import time
import json
import numpy as np
import random

# we need to import some python modules from the $SUMO_HOME/tools directory
if 'SUMO_HOME' in os.environ:
    tools = os.path.join(os.environ['SUMO_HOME'], 'tools')
    sys.path.append(tools)
else:
    sys.exit("please declare environment variable 'SUMO_HOME'")


from sumolib import checkBinary  # Checks for the binary in environ vars
import traci

def add_vehicle(): 
    additional_route_ID = traci.route.getIDList()
    no_of_cars = 60 - traci.simulation.getMinExpectedNumber()
    for i in range(no_of_cars):
        routeID = random.choice(additional_route_ID)
        while True:
            additional_veh_ID = random.randint(0,10000000)
            vehID = "addtionVehical."+str(additional_veh_ID)
            try:
                traci.vehicle.add(vehID, routeID, "car")
                break
            except:
                pass
def run():
    print('saving')
    step = 0
    traci.start([checkBinary('sumo'), "-c", "config.sumocfg", "--step-length", "0.5", '--save-state.rng', "--step-method.ballistic", "--no-step-log", "--no-warnings", "--tripinfo-output", "tripinfo.xml"])
    simulation_time = 10*60  # increasing this increases Memory usage
    while step <= simulation_time:
        print(step)
        add_vehicle() # adding vehicles to the network
        traci.simulationStep()
        step += traci.simulation.getDeltaT()
        if step % 5 == 0:
            for _ in range(200): 
                traci.simulation.saveState('saved_state')
                # Save state and work on it and then load back the state
                traci.simulation.loadState('saved_state') # this uses a lot of memory, comment it to see the difference
    traci.close()     
        
    
# main entry point
if __name__ == "__main__":
    run()
    
