//------------------------------------------------------------------------------
//	Copyright (C) 2009 Humboldt-Universitaet zu Berlin
//
//	This library is free software; you can redistribute it and/or
//	modify it under the terms of the GNU Lesser General Public
//	License as published by the Free Software Foundation; either
//	version 2.1 of the License, or (at your option) any later version.
//
//	This library is distributed in the hope that it will be useful,
//	but WITHOUT ANY WARRANTY; without even the implied warranty of
//	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
//	Lesser General Public License for more details.
//
//	You should have received a copy of the GNU Lesser General Public
//	License along with this library; if not, write to the Free Software
//	Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
//------------------------------------------------------------------------------

/**
 * @file Example_Process_Deletion.cpp
 * @author Ronald Kluth
 * @date created at 2010/04/24
 * @brief Example demonstrating how to delete terminated processes
 * @since 3.0
 */

/**
 * @example Example_Process_Deletion.cpp
 * The usage of ODEMx process memory management is demonstrated.
 *
 * For this purpose, Processes are created, activated and immediately
 * terminated after running once. These Process objects are then automatically
 * destroyed.
 */

#include <odemx/odemx.h>
using namespace odemx;
using namespace odemx::base;

#include <iostream>

//
// Process class that shows when a process is active and thus becomes terminated
// after finishing its main function. Logging in the destructor shows when
// the objects get destroyed.
//
class TestProcess: public Process {
public:
	TestProcess(): Process( odemx::getDefaultSimulation(), "TestProcess" ) {}
	~TestProcess() { info << log( "process destroyed" ); }
	virtual int main()
	{
		info << log( "active" );
		return 0;
	}
};

//
// A generator event class that creates and schedules processes.
//
class Generator: public Event {
public:
	Generator( int count ): Event( odemx::getDefaultSimulation(), "Generator" )
	, 	count_( count ) {}
	virtual void eventAction()
	{
		for( int i = 0; i < count_; ++i )
		{
			info << log( "new process" );
			Process* p = new TestProcess();
			p->activateIn( 10 );
		}
	}
private:
	int count_;
};

int main()
{
	Simulation& sim = getDefaultSimulation();
	//
	// In order to have ODEMx delete terminated processes during a simulation
	// run, the method @c autoDeleteProcesses must be called.
	//
	sim.autoDeleteProcesses();
	sim.addConsumer( data::channel_id::info,
			data::output::OStreamWriter::create( std::cout ) );
	//
	// All processes are created and scheduled at once, but each is
	// deleted right after its execution when control goes back to the
	// simulation context.
	//
	Generator gen( 5 );
	gen.schedule();
	sim.runUntil( 15 );
}
