// ----------------------------------------------------------------------------
// Copyright (C) 2008 Francisco Grimaldo, Miguel Lozano, Fernando Barber
// 
// 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
// 
// To contact the authors:
// francisco.grimaldo@uv.es, miguel.lozano@uv.es, fernando.barber@uv.es
// http://www.uv.es/grimo
// http://grev.uv.es
//
//----------------------------------------------------------------------------

package jmadem;

import jason.asSemantics.DefaultInternalAction;
import jason.asSemantics.TransitionSystem;
import jason.asSemantics.Unifier;
import jason.asSyntax.ASSyntax;
import jason.asSyntax.Literal;
import jason.asSyntax.Term;
import jason.asSyntax.ListTermImpl;
import jason.asSyntax.NumberTermImpl;
import jason.asSyntax.Atom;

import java.util.logging.Logger;
import java.util.Map;
import java.util.concurrent.ConcurrentMap;
import java.util.Iterator;

/** 
 * Internal function for getting the utility weights being used by the MADeM agent.
 * <p>
 * <b>Use:</b> <br/> <tt>jmadem.get_list_of_utility_weights([ [UtilityName, Weight] | ListOfPairs ])</tt>
 * </p>
 *
 * @author Francisco Grimaldo
 */
public class get_list_of_utility_weights extends DefaultInternalAction  {

	private static final long serialVersionUID = 9087581632448543187L;
	
	Logger logger = Logger.getLogger(get_list_of_utility_weights.class.getName());

	@Override
	public Object execute(TransitionSystem ts, Unifier un, Term[] args) throws Exception 
	{
		try
		{
			// Get the utility weights
			MADeMAgArch agArch = (MADeMAgArch)ts.getUserAgArch();
			ConcurrentMap<Atom, Float> utilityWeights = agArch.getUtilityWeights();

			// Construct response
			ListTermImpl res = new ListTermImpl();
			Literal pair;
			Iterator<Map.Entry<Atom, Float>> it = utilityWeights.entrySet().iterator();
			Map.Entry<Atom, Float> element;
			while (it.hasNext())
			{
				element = it.next();
				pair = ASSyntax.createLiteral("jmadem_utility_weight", 
	                      element.getKey(),
	                      new NumberTermImpl((double) element.getValue()));
				res.add(pair);
			}			
			
			// Send response back 			
			return un.unifies(args[0], res);
		}
		catch (Exception e)
		{
			logger.severe("Error getting utility weights.");
			e.printStackTrace();
			return false;
		}
    }
}
