/*
 * ECatalog is a database front-end, with two main features:
 * 1. Use of preferences
 *  A preference-based approach, where the user is allowed to define the importance of each criterion.
 *  Then the items are ranked accordingly to his criteria.
 * 2. Trade-off analysis
 *  A cooperative database approach, where the system "argues" with the user about his criteria.
 *  When there are no matching items, the system explains the minimal conflicting set and
 *  give some possible strong and weak relaxations about his criteria.
 * This package also containts the software and the set-up details used for our User Study,
 * comparing the use or not of the two previous features mentioned above.
 *
 * Copyright (C) 2006 David Portabella Clotet, Artificial Intelligence Laboratory, EPFL
 * 
 * This file is part of ecatalog-1.0.zip
 * 
 * ECatalog is free software and a free user study set-up;
 * 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.
 * 
 * ECatalog 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 ECatalog; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 * 
 * @version 1.0
 * @author David Portabella
 * To contact the author:
 * email: david@portabella.name and david.portabella@epfl.ch
 * 
 * More information about ECatalog:
 *  http://sourceforge.net/projects/ecatalog/
 *  http://icwww.epfl.ch/~portabel/ecatalogs/
 */

package ecatalog.gui.criteriaSelection;

import ecatalog.ECatalog;
import ecatalog.db.Attribute;
import ecatalog.db.AttributeConstraint;
import ecatalog.db.SimpleAttributeConstraint;
import ecatalog.db.MultipleValuesConstraint;

import java.util.Vector;
import java.util.Arrays;
import java.util.Comparator;
import java.sql.SQLException;

import dpc.utils.ArrayConverter;

class Util {

    /* sort the list of values 
     * @param c   the constraint involved
     * @param filterIncompatibleValues   whether to exclude or not the incompatible values
     * @param direction  -1 means shows first the values with less currentNbrCompatibleItemsIfValueSelected. 1 the opposite. and 0 means no ordering (so, alfabethic filtering
     */
    public static int[] getSortedIndex(AttributeConstraint c, String textFilter, boolean filterIncompatibleValues, int direction) {
	try {
	    //System.out.println("getSortedIndex: " + c.getAttribute().getLabel());
	    Integer[] sortedIndex;

	    CountInterface ci = createCountInterface(c);

	    int nbrDistinctValues = c.getAttribute().getNbrDistinctValues();
	    if (textFilter != null) {
		textFilter = textFilter.trim().toLowerCase();
		if (textFilter.equals(""))
		    textFilter = null;
	    }

	    if (!filterIncompatibleValues && textFilter == null) {
		sortedIndex = new Integer[nbrDistinctValues];
		for (int i = 0; i < nbrDistinctValues; i++)
		    sortedIndex[i] = i;
	    } else {
		Attribute at = c.getAttribute();
		Vector<Integer> sortedIndexVector = new Vector<Integer>();
		for (int i = 0; i < nbrDistinctValues; i++) {
		    int nbr = ci.getNbrItemsForValue(i);
		    if ((!filterIncompatibleValues || nbr > 0) && (textFilter == null || at.getValueString(i).toLowerCase().contains(textFilter)))
			sortedIndexVector.add(i);
		}
		sortedIndex = sortedIndexVector.toArray(new Integer[sortedIndexVector.size()]);
	    }
	
	    if (direction != 0) {
		class MyComparator implements Comparator {
		    CountInterface ci;
		    int moreId, lessId;
		    MyComparator(CountInterface ci, int direction) {
			this.ci = ci; 
			moreId = (direction == 1) ? 1 : -1;
			lessId = (direction == 1) ? -1 : 1;
		    }
		    public int compare(Object o1, Object o2) {
			try {
			    double diff =
				ci.getNbrItemsForValue((Integer)o2) - ci.getNbrItemsForValue((Integer)o1);
			    if (diff == 0.0)
				return 0;
			    return (diff < 0) ? moreId : lessId;
			} catch (SQLException e) {
			    ECatalog.error(e); 
			    throw new Error(); //it is already done, but to avoid the java compiling error
			}
		    }
		    public boolean equals(Object obj) { return this.equals(obj); }
		};
		Arrays.sort(sortedIndex, new MyComparator(ci, direction));
	    }
	    return ArrayConverter.toIntegers(sortedIndex);
	}
	catch (SQLException e) { 
	    ECatalog.error(e); 
	    throw new Error(); //it is already done, but to avoid the java compiling error
	}
    }

    static CountInterface createCountInterface(AttributeConstraint c) {
	if (c instanceof SimpleAttributeConstraint)
	    return new SimpleAttributeConstraintCountInterface((SimpleAttributeConstraint)c);
	else if (c instanceof MultipleValuesConstraint)
	    return new MultipleValuesConstraintCountInterface((MultipleValuesConstraint)c);
	else {
	    ECatalog.error(new Error(c.getClass().getName() + " CountInterface not supported"));
	    throw new Error(); //it is already done, but to avoid the java compiling error
	}
    }
}

abstract class CountInterface {
    abstract int getNbrItemsForValue(int valueIndex) throws SQLException;
}
class SimpleAttributeConstraintCountInterface extends CountInterface {
    SimpleAttributeConstraint c;
    SimpleAttributeConstraintCountInterface(SimpleAttributeConstraint c) { this.c = c; }
    int getNbrItemsForValue(int valueIndex) throws SQLException { return c.getCurrentNbrCompatibleItemsIfValueSelected(valueIndex); }
}
class MultipleValuesConstraintCountInterface extends CountInterface {
    MultipleValuesConstraint c;
    MultipleValuesConstraintCountInterface(MultipleValuesConstraint c) { this.c = c; }
    int getNbrItemsForValue(int valueIndex) throws SQLException { return c.getCurrentNbrCompatibleItemsIfValueAdded(valueIndex); }
}


