#!/usr/bin/python3
import traci
# import time
# import csv
from sumolib import checkBinary

import argparse

parser = argparse.ArgumentParser(
    prog='compute-pass-per-vehicle-with-sumo.py',
    usage='%(prog)s [optional arguments] -- SUMOARGS',
    description='Run SUMO and compute passengers per vehicle',
    epilog="Examples\n"
          '  compute-pass-per-vehicle-with-sumo.py -f 500 -l 1000 -v tram1 tram4 -- -c loopAraya.sumocfg\n'
          '    run SUMO with loopAraya.sumocfg, collect data between 500 and 1000 sec for vehicles tram1 and tram4\n'
          '  compute-pass-per-vehicle-with-sumo.py -f 3600 -t 4000 -v 0 1 2 3 -- -c test.sumocfg\n'
          '    run SUMO with test.sumocfg, collect data between 3600 and 4000 sec for vehicles 0,1,2 and 3'
, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument('-f','--first', type=int, default=0, help='From time')
parser.add_argument('-l','--last', type=int, default=3600, help='To time')
parser.add_argument('-v','--vehicles', nargs='+', help='Vehicles to observe')
parser.add_argument('-g','--gui', action='store_true', help='Use sumo-gui')
parser.add_argument('sumoargs', nargs='+')
args = parser.parse_args()

if args.gui:
  sumoBinary = checkBinary ("sumo-gui")
else:
  sumoBinary = checkBinary ("sumo")

sumoCmd = [sumoBinary, "--quit-on-end", "--start"]
sumoCmd.extend(args.sumoargs)

print('Run ' + ' '.join(sumoCmd))

traci.start(sumoCmd)
step = 0
csvfile = open('passengers.csv', 'w')
energyfile = open("batteryCapacity.csv", "w")


# plugins for the main loop fror different questions
def fueling_behavior(current_time):
    if 3600 <= current_time <= 60000:
        vehicle = ["0", "1", "2", "3", "4", "5", "6", "7"]
        
        simTime = [str(current_time)]
        if args.first <= current_time:
            for i in vehicle:
                try:
                    currentBusFuel = traci.vehicle.getParameter(i, "device.battery.actualBatteryCapacity")
                    busCapacity = traci.vehicle.getPersonNumber(i) 
#                     if currentBusFuel <= "553000" and busCapacity == 0:
#                         traci.vehicle.changeTarget(i,"-7855681#1")  
                except:
                    currentBusFuel = "0"
#                 simTime.append(str(currentBusFuel))
#                 simTime.append(str(busCapacity))
#             
#             
#             print(simTime)
#             print(','.join(simTime), file=energyfile, flush=True)
        
            for e in vehicle:
                actualFuelLevel = traci.vehicle.getParameter(e, "device.battery.actualBatteryCapacity")
                numBusRiders = traci.vehicle.getPersonNumber(e)
                try:
                    if actualFuelLevel <= "553000" and numBusRiders == 0:
                        traci.vehicle.setChargingStationStop(e,"chargingStation_-7855681#1_0_0", 300, 0)
                except:
                    actualFuelLevel = 0
                simTime.append(str(currentBusFuel))
                simTime.append(str(busCapacity))
            print(simTime)
            print(','.join(simTime), file=energyfile, flush=True)    
            
#       print ('%.0f Vehicle %s Battery %8.2f' % (current_time, '0', float(current_fuel_Level)))         
        

def maintain_headway(current_time):
  #For Green Route Buses (ONLY)
  # Detect Vehicle 6 so that Vehicle 5 can slow down
  if current_time >= 3600:
    secondVehicle = '5'
    leader = traci.vehicle.getLeader(secondVehicle, 5)
    atBusStop = traci.vehicle.isAtBusStop(secondVehicle)
    if (atBusStop != False) and leader != None:
        print("At timestep %.0f JagTran %s is at Bus Stop" % (current_time, secondVehicle))
        print('leader', leader)
        #print('Leader of 5 %s' % leader_id)
        if leader[0] == "6" and leader[1] <= 10:
             oldSpeed = traci.vehicle.getSpeed(secondVehicle)
             traci.vehicle.slowDown(secondVehicle, 0.02, 65)
             print('%.0f Slowdown vehicle %s with current speed %4.1f' % (current_time, secondVehicle, oldSpeed))

#              traci.vehicle.getNextStops(secondVehicle)
#              traci.vehicle.replaceStop(secondVehicle, 1, "GreekRowSB20", 12.10, 1, 7.15, 460, 0)
#             traci.vehicle.setSpeed(secondVehicle, 0.00)
            
#         if leader_id >= ("6", 15):
#             traci.vehicle.openGap("5", 360, 1850, 300, -0.5, -0.5, "6")
#             traci.vehicle.getSt

# main loop, current_time serves as step
while traci.simulation.getMinExpectedNumber() > 0:
  traci.simulationStep()
  current_time = traci.simulation.getTime()

  # Execution for Beginning of Simulation
  # do nothing special
  # Execution for collecting Ridership within Bus Vehicles
  # call plugins
  #maintain_headway(current_time)
  fueling_behavior(current_time)
  if args.first <= step:
        # This set of code gets the number of riders currently within the bus
        list_of_ridership = [str(current_time)]
        for id in args.vehicles:
          # take care, if vehicle does not exist
          try:
            ridership = traci.vehicle.getPersonNumber(id)
          except:
            ridership = 0
          list_of_ridership.append(str(ridership))
        # create a comma-separated list
        print(','.join(list_of_ridership), file=csvfile, flush=True)
  if step > args.last:
    break
  step += 1 # not really used any more

csvfile.close()
traci.close()

#       current_fuel_Level_Red = traci.vehicle.getParameter(vehicle[0], "device.battery.actualBatteryCapacity")
#       current_fuel_Level_Blue1 = traci.vehicle.getParameter(vehicle[1], "device.battery.actualBatteryCapacity")
#       current_fuel_Level_Blue2 = traci.vehicle.getParameter(vehicle[2], "device.battery.actualBatteryCapacity")
#       current_fuel_Level_Yellow1 = traci.vehicle.getParameter(vehicle[3], "device.battery.actualBatteryCapacity")
#       current_fuel_Level_Yellow2 = traci.vehicle.getParameter(vehicle[4], "device.battery.actualBatteryCapacity")
#       current_fuel_Level_Green1 = traci.vehicle.getParameter(vehicle[5], "device.battery.actualBatteryCapacity")
#       current_fuel_Level_Green2 = traci.vehicle.getParameter(vehicle[6], "device.battery.actualBatteryCapacity")
#       current_fuel_Level_Orange = traci.vehicle.getParameter(vehicle[7], "device.battery.actualBatteryCapacity")
#       print("At timestep %8.2f: %8.2f, %8.2f, %8.2f, %8.2f, %8.2f, %8.2f, %8.2f, %8.2f" % (current_time, float(current_fuel_Level_Red), float(current_fuel_Level_Blue1),
#                                                                         float(current_fuel_Level_Blue2), float(current_fuel_Level_Yellow1), float(current_fuel_Level_Yellow2),
#                                                                         float(current_fuel_Level_Green1), float(current_fuel_Level_Green2), float(current_fuel_Level_Orange)))
