/*
 * $Id: Instance_getParam.cpp 97 2008-12-19 15:34:00Z rosiere $
 *
 * [ Description ]
 * 
 */

#include "Behavioural/Configuration/include/Instance.h"

namespace morpheo {
namespace behavioural {
namespace configuration {

#undef  FUNCTION
#define FUNCTION "Instance::getParam"
  std::string Instance::getParam (const char * name, ...)
  {
    log_begin(Configuration,FUNCTION);

    std::string value = "";
    
    // Go to the good component
    list_parameters_t * list_parameters = _list_parameters;
    list_components_t * list_components = _list_components;
    
    {
      va_list args;
      va_start(args, name);

      std::string component = "";
      std::string id = "";
      std::string tmp;
      while (((tmp = va_arg(args,const char *)) != "") and
             (value  == ""))
        {
          // 2 string :
          //   * first  : component
          //   * second : id

          component = tmp;

          if ((tmp = va_arg(args,const char *)) == "")
            throw ERRORMORPHEO(FUNCTION,_("Must have two name : first is the component's name, second is the identification\n"));
          id = tmp;

          list_instances_t::iterator it=((*list_components)[component]).find(id);
          
          if (it == ((*list_components)[component]).end())
            {
            //log_printf(INFO,Configuration,FUNCTION,_("Component \"%s[%s]\" is not define, take default value for parameter \"%s\"."),component.c_str(),id.c_str(),name);

              value = _generator->getParam(name)->_default;
            }
          else
            {
              list_parameters = it->second->_list_parameters;
              list_components = it->second->_list_components;
            }
        }

      if (value == "")
        {
          // no default value : component is find
          
          // Test if parameters exist
//           std::map<std::string, Parameter_affectation *>
          list_parameters_t::iterator it=(*list_parameters).find(name);
          if (it == (*list_parameters).end())
            {
            //log_printf(INFO,Configuration,FUNCTION,_("Component \"%s[%s]\" is define, but parameter \"%s\" is not define. Take default value."),component.c_str(),id.c_str(),name);

              value = _generator->getParam(name)->_default;
            }
          else
            {
              if (it->second->_use)
                throw ERRORMORPHEO(FUNCTION,toString(_("Parameter \"%s\" is already used.\n"),name));

              value = it->second->_value;
              it->second->_use = true; // now, this parameters is use
            }
        }

      va_end(args);
    }
    
  //log_printf(INFO,Configuration,FUNCTION,_("Parameters \"%s\" = %s."),name,value.c_str());

    log_end(Configuration,FUNCTION);

    return value;
  };

}; // end namespace configuration
}; // end namespace behavioural
}; // end namespace morpheo              
