/*
 * 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.db;

import ecatalog.ECatalog;

import utils.OrderedSet;

import dpc.utils.TextUtil;
import dpc.utils.SqlUtil;
import dpc.utils.ToStringInterface;
import dpc.utils.DebugUtil;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Vector;

import dpc.utils.DebugUtil;

//import org.apache.bsf.BSFException;

/* A constraints that lets specify a set of values, one of which must be the solution in order to be satisfied.
 * Or noneof...
 * Here the boolean variable "detailsDefined" from Constraint.java is not used!! Instead, use the function areDetailsDefined() or removeDetails()
*/

public class MultipleValuesConstraint extends AttributeConstraint {
    protected OrderedSet<Integer>valuesIndex = new OrderedSet<Integer>();
    EscapeToStringFunction escapeToStringFunction = new EscapeToStringFunction();

    public enum Type{INCLUDE, EXCLUDE};
    Type type;

    protected int[] currentNbrCompatibleItemsIfValueSelected;
    protected int currentNbrCompatibleItemsIfExampleValueSelected;
    protected boolean[] valueSatisfiesConstraint = null;
    protected int currentNbrCompatibleItemsExcludingThisConstraint;

    String withConstraintStringFunction;
    String relaxConstraintStringFunction;

    public MultipleValuesConstraint(Type type, Attribute attribute, Database db, Weight weight) { 
	super(attribute, db, weight);
	this.type = type;
	withConstraintStringFunction = attribute.config.getWithConstraintStringFunction();
	relaxConstraintStringFunction = attribute.config.getRelaxConstraintStringFunction();
	update();
    }

    public Type getType() {
	return type;
    }

    public boolean areDetailsDefined() {
	return (valuesIndex.size() > 0);
    }

    public void removeDetails() { 
	//DebugUtil.printTrace("c[" + attribute.getId() +"].removeDetails()");
	valuesIndex.removeAllElements();
    }

    public void addValueIndex(int valueIndex) {
	valuesIndex.add((Integer)valueIndex);
    }

    public void setValueIndex(int valueIndex, int position) {
	valuesIndex.setElementAt((Integer) valueIndex, position);
    }

    public void removeValueIndex(int valueIndex) {
	valuesIndex.remove((Integer)valueIndex);
    }

    public int getNbrOfvalues() {
	//DebugUtil.printTrace("c[" + attribute.getId() +"].getNbrOfvalues()=" + valuesIndex.size());
	return valuesIndex.size();
    }

    public int getValueIndexAt(int valuePosition) {
	return valuesIndex.getElementAt(valuePosition);
    }

    public boolean containtsValueIndex(int valueIndex) {
	return (valuesIndex.contains((Integer)valueIndex));
    }

    public String getSqlClauseTerm() {
	if (areDetailsDefined() == false)
	    return null;
	String op = (type == Type.INCLUDE) ? "IN" : "NOT IN";
	return TextUtil.getListString(valuesIndex.getCollection(), attribute.id + " " + op + "(", ")", escapeToStringFunction, ", ", null);
    }

    public String getTextClauseTerm() {
	if (areDetailsDefined() == false)
	    return null;
	String text;
	if (getNbrOfvalues() == 1) {
	    String op = (type == Type.INCLUDE) ? "=" : "not =";
	    text = attribute.label + " " + op + " " + attribute.getValueString(getValueIndexAt(0));
	} else {
	    String op = (type == Type.INCLUDE) ? "Selected" : "Excluded";
	    text = op + " values for " + attribute.label;
	}

	return text;
    }

    public String getConstraintTypeDescription() {
	return getClass().getName() + "[type=" + type + "]";
    }

    public String toString() {
	return "MultipleValuesConstraint(detailsDefined=" + areDetailsDefined() + ",type=" + type + ", valuesId=" + TextUtil.getListString(valuesIndex.getCollection(), "{", "}", escapeToStringFunction, ", ", null);
    }
    
    public Object clone() {
 	MultipleValuesConstraint clone = new MultipleValuesConstraint(type, attribute, db, weight);
	clone.valuesIndex.addAll(valuesIndex);

	return clone;
    }
    
    public void importDetails(Constraint sourceConstraint) {
	valuesIndex.removeAllElements();
	if (!sourceConstraint.areDetailsDefined())
	    return;

	if (sourceConstraint instanceof MultipleValuesConstraint) {
	    valuesIndex.addAll(((MultipleValuesConstraint)sourceConstraint).valuesIndex);
	} else if (sourceConstraint instanceof SimpleAttributeConstraint) {
	    valuesIndex.add((Integer) ((SimpleAttributeConstraint)sourceConstraint).getValueIndex());
	}
    }
    
    /* update (or mark to be updated) the proper context variables */
    public void update() {
	valueSatisfiesConstraint = null;
	currentNbrCompatibleItemsExcludingThisConstraint = -1;
	currentNbrCompatibleItemsIfValueSelected = null;
	currentNbrCompatibleItemsIfExampleValueSelected = -1;
    }

    public boolean doesAttributeValueSatisfyConstraint(Attribute attribute, int valueIndex) {
	if (!areDetailsDefined() || this.attribute != attribute)
	    return true;

	if (valueSatisfiesConstraint == null)
	    computeValueSatisfiesConstraint();
	return valueSatisfiesConstraint[valueIndex];
    }

    public double getPenaltyForItem(Item item) throws SQLException{
	return doesAttributeValueSatisfyConstraint(attribute, attribute.getValueIndex(item)) ? 0.0 : -1.5;
    }


    /* Current Number Of Compatible Items, Excluding This Constraint; Is there a better name for this, than nbrItems??   */
    public int getCurrentNbrCompatibleItemsExcludingThisConstraint() throws SQLException { 
	if (currentNbrCompatibleItemsExcludingThisConstraint == -1)
	    computeCurrentNbrCompatibleItemsExcludingThisConstraint();
	return currentNbrCompatibleItemsExcludingThisConstraint; 
    }

    public int getCurrentNbrCompatibleItemsIfValueAdded(int addedValueIndex) throws SQLException {
	if (currentNbrCompatibleItemsIfValueSelected == null) {
	    if (valuesIndex.isEmpty() && addedValueIndex == attribute.getCurrentExampleValueIndex()) {
		if (currentNbrCompatibleItemsIfExampleValueSelected == -1)
		    computeCurrentNbrCompatibleItemsIfExampleValueSelected();
		return (type == Type.INCLUDE) 
		    ? currentNbrCompatibleItemsIfExampleValueSelected
		    : (getCurrentNbrCompatibleItemsExcludingThisConstraint() - currentNbrCompatibleItemsIfExampleValueSelected);
	    } else {
		computeCurrentNbrCompatibleItemsIfValueSelected();
	    }
	}
	int nbrItems = 0;
	for (Integer valueIndex : valuesIndex.getCollection())
	    nbrItems += currentNbrCompatibleItemsIfValueSelected[valueIndex];
	if (!valuesIndex.contains((Integer)addedValueIndex))
	    nbrItems += currentNbrCompatibleItemsIfValueSelected[addedValueIndex];

	return (type == Type.INCLUDE) 
	    ? nbrItems
	    : (getCurrentNbrCompatibleItemsExcludingThisConstraint() - nbrItems);
    }

    /* removedValueIndex must already be in the set, otherwise the result is incorrect */
    public int getCurrentNbrCompatibleItemsIfValueRemoved(int removedValueIndex) throws SQLException {
	if (valuesIndex.size() == 1 && valuesIndex.contains((Integer) removedValueIndex))
	    return getCurrentNbrCompatibleItemsExcludingThisConstraint();

	if (currentNbrCompatibleItemsIfValueSelected == null) 
	    computeCurrentNbrCompatibleItemsIfValueSelected();

	int nbrItems = 0;
	for (Integer valueIndex : valuesIndex.getCollection())
	    nbrItems += currentNbrCompatibleItemsIfValueSelected[valueIndex];

	nbrItems -= currentNbrCompatibleItemsIfValueSelected[removedValueIndex];

	return (type == Type.INCLUDE) 
	    ? nbrItems
	    : (getCurrentNbrCompatibleItemsExcludingThisConstraint() - nbrItems);
    }

    /* removedValueIndex must already be in the set, otherwise the result is incorrect */
    public int getCurrentNbrCompatibleItemsIfValueChanged(int removedValueIndex, int addedValueIndex) throws SQLException {
	if (currentNbrCompatibleItemsIfValueSelected == null) 
	    computeCurrentNbrCompatibleItemsIfValueSelected();

	int nbrItems = 0;
	for (Integer valueIndex : valuesIndex.getCollection())
	    nbrItems += currentNbrCompatibleItemsIfValueSelected[valueIndex];

	if (removedValueIndex != addedValueIndex) {
	    nbrItems -= currentNbrCompatibleItemsIfValueSelected[removedValueIndex];
	    if (!valuesIndex.contains((Integer)addedValueIndex))
		nbrItems += currentNbrCompatibleItemsIfValueSelected[addedValueIndex];
	}

	return (type == Type.INCLUDE) 
	    ? nbrItems
	    : (getCurrentNbrCompatibleItemsExcludingThisConstraint() - nbrItems);
    }


    protected void computeCurrentNbrCompatibleItemsExcludingThisConstraint() throws SQLException{
	computeCurrentNbrCompatibleItemsIfValueSelected();
    }

    protected void computeValueSatisfiesConstraint() {
	valueSatisfiesConstraint = new boolean[attribute.nbrDistinctValues];
	if (!areDetailsDefined()) {
	    for (int valueIndex = 0; valueIndex < attribute.nbrDistinctValues; valueIndex++)
		valueSatisfiesConstraint[valueIndex] = true;
	    return;
	}

	if (type == Type.INCLUDE) {
	    for (Integer valueIndex : valuesIndex.getCollection())
		valueSatisfiesConstraint[valueIndex] = true;
	} else {
	    for (int valueIndex = 0; valueIndex < attribute.nbrDistinctValues; valueIndex++)
		valueSatisfiesConstraint[valueIndex] = true;
	    for (Integer valueIndex : valuesIndex.getCollection())
		valueSatisfiesConstraint[valueIndex] = false;
	}
    }

    /* Compute the currentNbrCompatibleItems If Value (only that) is selected */
    protected void computeCurrentNbrCompatibleItemsIfValueSelected() throws SQLException {
	ECatalog.lowlevelMsg("EXPENSIVE: constraint[" + attribute.getLabel() + "].computeCurrentNbrCompatibleItemsIfValueSelected()");
	String query="SELECT " + attribute.id + ", COUNT(*) FROM " + db.fromClause + " WHERE " + db.getConstraintsClauseExcept(this) + " GROUP BY " + attribute.id + " ORDER BY " + attribute.id;
	ResultSet rs = db.executeQuery(query);

	currentNbrCompatibleItemsExcludingThisConstraint = 0;
	currentNbrCompatibleItemsIfValueSelected = new int[attribute.nbrDistinctValues];  // reset to zero
	while (rs.next()) {
	    int index = attribute.getValueIndex(rs, 1);
	    assert(index != -1);
	    int nbr = rs.getInt(2);
	    currentNbrCompatibleItemsIfValueSelected[index] = nbr;
	    currentNbrCompatibleItemsExcludingThisConstraint += nbr;
	}
	rs.close();
    }

    /* Compute the currentNbrCompatibleItems If the Example Value (only that) is selected */
    protected void computeCurrentNbrCompatibleItemsIfExampleValueSelected() throws SQLException {
	ECatalog.lowlevelMsg("EXPENSIVE: constraint[" + attribute.getLabel() + "].computeCurrentNbrCompatibleItemsIfExampleValueSelected()");

	//Get the WHERE clause for the example value
	String exampleClause = EqualConstraint.getSqlClauseTerm(attribute, attribute.getCurrentExampleValueIndex());

	//get currentNbrCompatibleItemsIfExampleValueSelected
	String query="SELECT COUNT(*) FROM " + db.fromClause + " WHERE " + db.getConstraintsClauseExcept(this) + " AND " + exampleClause;
	currentNbrCompatibleItemsIfExampleValueSelected = SqlUtil.getUniqueInt(db.executeQuery(query));
    }


    public String getWithConstraintString() {
	//DebugUtil.printTrace();
	if (withConstraintStringFunction == null)
	    return getTextClauseTerm();

	try {
	    StringBuffer params = new StringBuffer();
	    params.append("var valuesId = new Array(" + valuesIndex.size() + ");");
	    for (int i = 0; i < valuesIndex.size(); i++)
		params.append("valuesId[" + i + "] = " + attribute.getDbValueString(valuesIndex.getElementAt(i), true) + ";");
	    params.append("constraintType = \"" + this.getClass().getName() + "\"; type=\"" + type.toString() + "\";");
	    Object result = db.scriptEval(params.append(withConstraintStringFunction).toString());
	    if (result == null)
		return getTextClauseTerm();
	    return result.toString();
	} catch (Exception e) { 
	    ECatalog.error(new Error(e)); 
	    throw new Error(); //it is already done, but to avoid the java compiling error
	}
    }


    public String getRelaxConstraintString() {
	//DebugUtil.printTrace();
	return getTextClauseTerm();
	//TODO
    }


    class EscapeToStringFunction implements ToStringInterface {
	public String toString(Object valueIndex) {
	    return attribute.getDbValueString((Integer)valueIndex, true);
	}
    }
}


