#include "traffic_agent.h"

void LaneHandler::connect_data(BaseTrafficAgent& agent0)
{
	agent = &agent0;
	agentin2input.set_connection(rv_inputs, agent->rv_inputs);
	ivec queue_index_tmp = agent->rv_queues.dataind(rv_queue);
	if (queue_index_tmp.length()==1){
		queue_index=queue_index_tmp(0);
	} else {
		bdm_error("queue " + lane.queue + " not found");
	}		
}

double LaneHandler::expected_output(double green_time){
	double last_inputs=0.0;
	


	agentin2input.filldown(agent->inputs, inputs);
	queue = agent->queues(queue_index);
	
	double exp_output=0.0;
	
	/////////
	
	agentin2input.filldown(agent->inputs,inputs);

	for (int i=0;i<inputs.length();i+=2) {
		last_inputs+=inputs(i);
	}

	exp_output=last_inputs*(green_time/agent->step_length);

	////////
	return exp_output;
}

double LaneHandler::expected_density() {
	double density=0.0;

	agentin2input.filldown(agent->inputs,inputs);
	
	for (int i=0;i<inputs.length();i+=2) {
		density+=inputs(i)/agent->step_length;
	}

	return density;
}

void BaseTrafficAgent::from_setting(const Setting& set)
{
	bdm::Participant::from_setting(set);
	
	// load from file
	if (set.exists("lanes")){
		Setting &Slanes=set["lanes"];
		lanes.set_length(Slanes.getLength());
		for(int l=0; l<lanes.length(); l++){
			lanes(l).from_setting(Slanes[l]);
		}
	}
	//UI::get(lanes,set,"lanes", UI::compulsory);
	UI::get(neighbours, set, "neighbours", UI::optional);
	UI::get(green_names, set, "green_names", UI::compulsory);
	UI::get(green_starts, set, "green_starts", UI::compulsory);
	UI::get(green_times, set, "green_times", UI::compulsory);
	UI::get(stage_names, set, "stage_names", UI::compulsory);
	UI::get(stage_times, set, "stage_times", UI::compulsory);
}
