package math;

import jason.JasonException;
import jason.asSemantics.DefaultInternalAction;
import jason.asSemantics.TransitionSystem;
import jason.asSemantics.Unifier;
import jason.asSyntax.ListTerm;
import jason.asSyntax.ListTermImpl;
import jason.asSyntax.Term;

import java.util.Collections;
import java.util.Comparator;

public class sortListOfPairs extends DefaultInternalAction {
    
    @Override
    public Object execute(TransitionSystem ts, Unifier un, Term[] args) throws Exception {
        try {
            ListTerm l1 = (ListTerm) args[0].clone();
            if (l1.isVar()) {
            	throw new JasonException("The first argument of .sort should not be a free variable.");
            }
            Collections.sort(l1, new MyComparator());
            return un.unifies(l1, args[1]);
        } catch (ArrayIndexOutOfBoundsException e) {
            throw new JasonException("The internal action 'sort' has not received two arguments.");
        } catch (JasonException e) {
        	throw e;
        } catch (Exception e) {
            throw new JasonException("Error in internal action 'sort': " + e, e);
        }    
    }
	
	class MyComparator implements Comparator
	{
		public int compare(Object e1, Object e2)
		{
		   	return (Integer.parseInt(((ListTermImpl)e1).get(0).toString()) - Integer.parseInt(((ListTermImpl)e2).get(0).toString()));
		}
	}
}
