
/*!
\file
\brief Application Arena - Interaction of Mulptiple Participants

Arena is a space in which participants (agents) live, there is one data source, arbitrary number of agents which communicate between each other.

\section ex Matlab usage
Execute command:
\code
>> arena(DS, {A1,A2,...},experiment,logger);
\endcode
where DS is a valid datasource and A1,... are agents and logger (optional) specified by their corresponding structures.
 */

#include <base/datasources.h>
#include <base/loggers.h>
#include <mpdm/arx_agent.h>

//#include "mex_datasource.h"

using namespace bdm;

#ifdef MEX
#include <itpp/itmex.h>
#include <mex/mex_BM.h>
#include <mex/mex_logger.h>
#include <mex/mex_datasource.h>
#include <mex/mex_function.h>

void mexFunction ( int n_output, mxArray *output[], int n_input, const mxArray *input[] ) {
	// Check the number of inputs and output arguments
	if ( n_input<2 ) mexErrMsgTxt ( "Usage:\n"
		                                "result=arena(system, agents, experiment, logger)\n"
		                                "  system     = struct('class','datasource',...);  % Estimated system\n"
		                                "  agents     = {struct('class','agent',...),  % Estimators\n"
		                                "                struct('class','agent',...),...} \n"
		                                "  === optional ==="
		                                "  experiment = struct('ndat',10);                 % number of data in experiment, full length of finite datasources, 10 otherwise \n"
		                                "  logger     = struct('class','mexlogger');       % How to store results, default=mexlog, i.e. matlab structure\n\n"
		                                "see documentation of classes datasource, BM, and mexlogger and their offsprings in BDM." );

	RV::clear_all();
	//CONFIG
	UImxArray Cfg;
	try {
		Cfg.addGroup ( input[0],"system" );
		Cfg.addList ( input[1],"agents" );
		if ( n_input>2 ) {
			Cfg.addGroup ( input[2],"experiment" );
		}
		if ( n_input>3 ) {
			Cfg.addGroup ( input[3],"logger" );
		}
	} catch ( SettingException e ) {
		it_error ( "error: "+string ( e.getPath() ) );
	}

	//DBG
// 	Cfg.writeFile ( "arena.cfg" );

#else
int main ( int argc, char* argv[] ) {
	const char *fname;
	if ( argc>1 ) {
		fname = argv[1];
	} else {
		fname="arena.cfg";
	}
	UIFile Cfg ( fname );
#endif

	RNG_randomize();
	
	shared_ptr<DS> Ds = UI::build<DS> ( Cfg, "system" );
	Array<shared_ptr<Participant> > Ags;
	UI::get ( Ags,Cfg, "agents" );
	int Ndat=100;
	int burnin=0;
	
	shared_ptr<epdf> burn_pdf; 
	
	if ( Cfg.exists ( "experiment" ) ) {
		Setting &exper=Cfg.getRoot()["experiment"];
		if (UI::get(Ndat, exper, "Ndat", UI::optional ) ) {
			bdm_assert ( Ndat<=Ds->max_length(), "Data source has less data then required" );
		};
		if (UI::get(burnin, exper, "burnin",UI::optional )){
			burn_pdf = UI::build<epdf>(exper,"burn_pdf", UI::compulsory);
			if (burn_pdf){
				bdm_assert(burn_pdf->dimension()==Ds->_urv()._dsize(),"Given burn_pdf does not match the DataSource");
			} else {
				bdm_error("burn_pdf not specified!");
			}
			
		}
	} else {
		if ( Ds->max_length() < std::numeric_limits< int >::max() ) {
			Ndat=Ds->max_length();
		}
		;// else Ndat=10;
	}
	shared_ptr<logger> L = UI::build<logger> ( Cfg, "logger",UI::optional );
	if ( !L ) {
#ifdef MEX
		//mex logger has only from_setting constructor - we  have to fill it...
		L=new mexlog ( Ndat );
#else
		L=new stdlog();
#endif
	}

	Config MsgStore;
	MsgStore.setAutoConvert(true);
	Setting& Queue = MsgStore.getRoot().add("queue", Setting::TypeList);
	
	Ds->log_register ( *L, "DS" );
	for ( int i=0; i<Ags.length(); i++ ) {
		Ags ( i )->log_register ( *L,Ags(i)->_name() ); // estimate
		Ags (i )->ds_register(*Ds);
	}
	L->init();

	vec glob_dt(Ds->_drv()._dsize() );
	vec glob_ut(Ds->_urv()._dsize() );
	for ( int tK=0;tK<Ndat;tK++ ) {
		Ds->log_write ( );
		Ds->getdata(glob_dt);
		
		for ( int i=0; i<Ags.length(); i++ ) {
			Ags(i) -> adapt(glob_dt);
		}
		for ( int i=0; i<Ags.length(); i++ ) {
			Ags(i) -> broadcast(Queue);
		}
		// parse message queue
		for ( int m=Queue.getLength()-1; m>=0; m-- ) { // go backwards - last mesages are discarded
			for ( int i=0; i<Ags.length(); i++ ) {
				Setting& msg=Queue[m];
				string m_to=msg["to"];
				if (m_to==Ags(i)->_name()) {
					Ags(i)->receive(msg);
					Queue.remove(m);
					break;
					// message delivered;
				}
			}
		}
		if (Queue.getLength()>0){bdm_error("undelivered messages - probably unknown neighbours");}
		
		if (tK <burnin){
			glob_ut=burn_pdf->sample();
		} else {
			for ( int i=0; i<Ags.length(); i++ ) {
				Ags(i) -> act(glob_ut);
			}
		}
		
		L->step();
		Ds->write(glob_ut);
		Ds->step();							// simulator step
		
		for ( int i=0; i<Ags.length(); i++ ) {
			Ags(i) -> step();
		}
		
	}

	L->finalize();
	// ------------------ End of routine -----------------------------

#ifdef MEX
	mexlog* mL=dynamic_cast<mexlog*> ( L.get() );

	if ( mL ) { // user wants output!!
		if ( n_output<1 ) mexErrMsgTxt ( "Wrong number of output variables!" );
		output[0] = mL->toCell();
		if (n_output>1) {
			mL->_setting_conf().setAutoConvert(true);
			output[1]= UImxArray::create_mxArray(mL->_setting_conf().getRoot());
		}
	}
#endif
}
