/***************************************************************************
 *   Copyright (C) 2005 by Robot Group Leipzig                             *
 *    martius@informatik.uni-leipzig.de                                    *
 *    fhesse@informatik.uni-leipzig.de                                     *
 *    der@informatik.uni-leipzig.de                                        *
 *    frankguettler@gmx.de                                                 *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 *   This program 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 General Public License for more details.                          *
 *                                                                         *
 *   You should have received a copy of the GNU General Public License     *
 *   along with this program; if not, write to the                         *
 *   Free Software Foundation, Inc.,                                       *
 *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
 *                                                                         *
 *   $Log: abstractmulticontroller.h,v $
 *   Revision 1.5  2008/04/17 14:54:44  martius
 *   randomGen added, which is a random generator with long period and an
 *    internal state. Each Agent has an instance and passed it to the controller
 *    and the wiring. This is good for
 *   a) repeatability on agent basis,
 *   b) parallel execution as done in ode_robots
 *
 *   Revision 1.4  2007/12/12 10:26:13  der
 *   MI: calculation of H(X) and H(Y|X) added
 *
 *   Revision 1.3  2007/04/19 13:48:20  robot3
 *   inserted new MI update function - needs O(1) instead of O(n^2)
 *
 *   Revision 1.2  2007/03/22 11:35:12  der
 *   corrected some bugs
 *
 *   Revision 1.1  2007/03/22 08:11:44  robot3
 *   abstract class for having multiple controllers for one Agent. See
 *   OneActiveMultiPassiveController for example.
 *

 *                                                                         *
 ***************************************************************************/
#ifndef __ABSTRACTMULTICONTROLLER_H
#define __ABSTRACTMULTICONTROLLER_H

#include "abstractcontrolleradapter.h"

/**
 * Abstract class (interface) for using multiple controller.
 * A controller gets a number of input sensor values each timestep
 *  and has to generate a number of output motor values
 *
 *
 * This is an abstract class, it's useful for implementing multicontrollers such as the
 * OneActiveMultiPassiveController, which can be used with all Controllers.
 *
 * Any MulitController implementing this class should overwrite the methods step(...) and
 * stepNoLearning(...).
 */
class AbstractMultiController : public AbstractControllerAdapter {
public:

  /// contructor (hint: use $ID$ for revision)
	AbstractMultiController(AbstractController* controller, std::string controllerName)
		: AbstractControllerAdapter(controller) {
			this->controllerNameList.push_back(controllerName);
		}

	virtual ~AbstractMultiController() {}

	/**
	 * Adds a passive controller to this MultiController. If the Agent calls step(..)
	 * or stepNoLearning(..), the MultiController calls not only the active controllers
	 * step(...) but also the step(...) of all the passive controllers. (same for
	 * stepNoLearning(..) ).
	 *
	 * Note: The initialisation of the MultiController with init(sensornumber, motornumber)
	 * must be called after all passive controllers are added, otherwise you must
	 * init the passive controller yourself (not recommended and can generate problems)
	 */
	virtual void addPassiveController(AbstractController* passiveController, std::string name) {
		if (passiveController!=0) {
			controllerList.push_back(passiveController);
			controllerNameList.push_back(name);
		} // otherwise return
	}

/****************************************************************************/
/*	AbstractMultiController should implement the following classes:        	*/
/*	AbstractController, Configurable, Inspectable, Storeable	            */
/****************************************************************************/


/****************************************************************************/
/*	BEGIN methods of AbstractController                                 	*/
/****************************************************************************/

	
  /** initialisation of the controller with the given sensor/ motornumber
   * Must NORMALLY be called before use. For all multicontroller
   * call first AbstractMultiController::init(sensornumber,motornumber)
   * if you overwrite this method
   */
	virtual void init(int sensornumber, int motornumber, RandGen* randGen = 0){
		AbstractControllerAdapter::init( sensornumber,motornumber);
		// init the other controllers
			for(std::list<AbstractController*>::iterator i=controllerList.begin(); i != controllerList.end(); i++){
				if (*i) (*i)->init(sensornumber,motornumber);
			}
	}

	  /** performs one step (includes learning).
      Calculates motor commands from sensor inputs.
	@param sensors sensors inputs scaled to [-1,1]
	@param sensornumber length of the sensor array
	@param motors motors outputs. MUST have enough space for motor values!
	@param motornumber length of the provided motor array
  */
	virtual void step(const sensor* sensors, int sensornumber,
	                  motor* motors, int motornumber)=0;

  /** performs one step without learning.
	@see step
  */
	virtual void stepNoLearning(const sensor* sensors , int sensornumber,
	                            motor* motors, int motornumber)=0;


/****************************************************************************/
/*	END methods of AbstractController                                 	    */
/****************************************************************************/

/****************************************************************************/
/*	BEGIN methods of Configurable                                       	*/
/****************************************************************************/



/****************************************************************************/
/*	END methods of Configurable                                      	    */
/****************************************************************************/

/****************************************************************************/
/*	BEGIN methods of Inspectable                                          	*/
/****************************************************************************/

  /** The list of the names of all internal parameters given by getInternalParams().
      The naming convention is "v[i]" for vectors
       and "A[i][j]" for matrices, where i, j start at 0.
	@return: list of keys
   */
	virtual iparamkeylist getInternalParamNames() const {
		std::list<iparamkey> keyList;
		// return all parameters from the other controllers
		
		// get the name of the controller
		std::list<std::string>::const_iterator cname=controllerNameList.begin();
		// first active controller
		std::list<iparamkey> controllerKeyList = controller->getInternalParamNames();
		for( std::list<iparamkey>::iterator key=controllerKeyList.begin();key!=controllerKeyList.end();key++ )
			keyList+= (*cname) + "" + (*key);
		
		// now the passive controllers
		for(std::list<AbstractController*>::const_iterator c=controllerList.begin(); c!= controllerList.end(); c++){
			if (*c) {
				cname++;
				controllerKeyList = (*c)->getInternalParamNames();
				for( std::list<iparamkey>::iterator key=controllerKeyList.begin();key!=controllerKeyList.end();key++ )
					keyList+= (*cname) + "" + (*key);
			}
		}		
		return keyList;
	}

	  /** @return: list of values
   */
	virtual iparamvallist getInternalParams() const {
		// return all parameters from the other controllers
		// return params from multicontroller itself
		std::list<iparamval> valList;
		// return all parameters from the other controllers
		
		// first active controller
		valList+= controller->getInternalParams();
		
		// now the passive controllers
		for(std::list<AbstractController*>::const_iterator c=controllerList.begin(); c!= controllerList.end(); c++) {
			valList+=(*c)->getInternalParams();
		}
		//int j=0;
		return valList;
	}

/****************************************************************************/
/*	END methods of Inspectable                                       	    */
/****************************************************************************/

/****************************************************************************/
/*	BEGIN methods of Storeable                                           	*/
/****************************************************************************/

  /** stores the object to the given file stream (binary).
  */
	virtual bool store(FILE* f) const {
		return controller->store(f);
		// store the other controllers
		// store values from multicontroller itself
	}

  /** loads the object from the given file stream (binary).
  */
	virtual bool restore(FILE* f) {
		return controller->restore(f);
		// restore the other controllers
		// restore values from multicontroller itself
	}

/****************************************************************************/
/*	END methods of Storeable                                          	    */
/****************************************************************************/

protected:
	// The AbstractController* controller is defined in AbstractControllerAdapter!
	std::list<AbstractController*> controllerList; // stores the other controllers
	std::list<std::string> controllerNameList; // stores the names of the controllers
};

#endif
