import Pkg
Pkg.activate(".")

import RidePooling
import RidePooling_eval
RP = RidePooling
ev = RidePooling_eval

if length(ARGS) == 3
    name = ARGS[3]
    settings_path = ARGS[2]
    index=eval(Meta.parse(ARGS[1]))
    println("Taken Command line values:\n\tIndex=$index\n\tsettings_path=$settings_path")
else
    throw("Value Error: Please give the command line arguments in the following order\nname\nsettings_path\nindex")
end


using DataFrames





include(settings_path)
#################################################################
### Setting everything up using the specified settings
include("functions.jl")
include(mapPath*"/maps.jl")
include(dispatcherPath *"/dispatchers.jl")

savePath = savePath * "$(String(request_type))/$cost/$name/"


index -= 2 #So that index starts at 0
dt_earliest_pickup = getX(index, dt_earliest_pickup_range..., ylen)
args = (;
routing = :lookup,
speed_dict = mapToSpeed[map],
speed_factor = mapTo_t0[map],
route_matrix = RP.get_route_matrix(mapPath*mapToMatrix[map]),
random_gens = Dict([request_type => [rng_type, dt_earliest_pickup], ]),
cost_idle_weight = getY(index, cost_idle_weight_range...),
resubmission_time_factor = getY(index, resubmission_time_factor_range...),
)
index +=2

#find the correct Dispatcher
dispatchers = dispatchers_ν_80
dispatchers = eachrow(dispatchers)
dispatcher = filter(x -> x.map == map && x.cost == cost && x.N_bus == N && x.rejection_criterion == rejection, dispatchers)[1] #TODO?If it is more than one it should be chosen randomly

# Change Dispatcher Format to fit keyword args
dispatcher = NamedTuple(dispatcher)

args = merge(args, dispatcher)
#############################Simulation####################################




# If index == 1: Do Vanilla simulation
if index ==1
	@time model=RP.get_model(;args...)
	model.request_type = :now
    @time RP.run!(model;requested=requested)
	
elseif index > 1

	@time model=RP.get_model(;args...)
    @time RP.run!(model;requested=requested)
	
end

#############################-Save Results-###############################

results = Dict()
for quan in req_quantitys_mean
	results[quan] = ev.quantity(quan, model)
end
for quan in req_quantitys_sum
	results[quan] = ev.sum(quan, model)
end

for quan in bus_quantitys
	results[quan] = ev.quantity(quan, model.agents, model)
end
for quan in model_quantitys
	f = @eval (ev.$quan)
	results[quan] = f(model)
end

results = NamedTuple(results)
data = merge(args, results)
data = DataFrame([data])
select!(data, Not(:route_matrix))
select!(data, Not(:routing))


using DelimitedFiles
open(savePath*"$(lpad(index, 5, "0")).csv", "w") do io
	writedlm(io, Iterators.flatten(([names(data)], eachrow(data))), ';')
end