/*
 * 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 dpc.utils.SqlUtil;
import java.util.Vector;
import java.sql.*;
import ecatalog.jaxb.ecatalogConfig.ECatalogConfigType;
import ecatalog.jaxb.ecatalogConfig.AttributeType;

/* An Attribute is a column in the SQL database.
 * All the distinct values for that column are retrieved in the subclass class of Attribute, typically valuesId[].
 * An valueIndex refers to the distinct values, e.g. valueIndex = 2 refers to valuesId[2]
 *
 * getValueString(valueIndex = 2) is a function that computes a string for this value,
 *  e.g. for a "Price" attribute, there could be valueId=20, getValueString()="20 CHF".
 *  this script function to compute this string is in the config file
 * 
 * At any given moment in time, if the solution space is not overconstrained, there is a column in the database
 * is selected as an example. To get the value for this attribute, call getCurrentExampleValueIndex() 
 */
public abstract class Attribute {
    protected String id;
    protected String label;
    protected int attributeIndex;
    protected int dbColumnIndex;
    protected AttributeType config;
    protected int nbrDistinctValues;
    protected int currentNbrCompatibleDistinctValues;
    protected String[] valuesString;
    protected boolean valueSatisfiesConstraints[];
    protected int currentExampleValueIndex;             //only valid in a non-overconstrained situation!!
    protected Database db;


    public Attribute(AttributeType config, Database db, int attributeIndex) {
	this.config = config;
	this.db = db;
	this.id = config.getId();
	this.label = config.getLabel();
	this.attributeIndex = attributeIndex;
	dbColumnIndex = attributeIndex + 1;
    }

    public  String getId() { return id; }

    public  String getLabel() { return label; }

    public  AttributeType getConfig() { return config; }

    public int getNbrDistinctValues() { return nbrDistinctValues; }

    /* Taking into account all user constraints (for all attributes) */
    public  int getCurrentNbrCompatibleDistinctValues() throws SQLException { 
	if (currentNbrCompatibleDistinctValues == -1)
	    computeCurrentNbrCompatibleDistinctValues();
	return currentNbrCompatibleDistinctValues; 
    }

    /* The value string representation for all the distinct possible values */
    public String getValueString(int valueIndex) { return valuesString[valueIndex]; }

    public int getCurrentExampleValueIndex() { return currentExampleValueIndex; }

    /* update (or mark to be updated) currentNbrCompatibleDistinctValues, valueSatisfiesConstraints */
    public void update() {
	currentNbrCompatibleDistinctValues = -1;
	valueSatisfiesConstraints = null;
	currentExampleValueIndex = -1;
    }

    public void updateExample(Item item) throws SQLException {
	currentExampleValueIndex = getValueIndex(item);
    }


    /* Indicates whether a value satisfies all the user constraints (without taking into account the database!)
     * i.e., valueSatisfiesConstraints[i] is true if valuesId[i] satisfies all the user constraints
     */
    public boolean getValueSatisfiesConstraints(int valueIndex) { 
	if (valueSatisfiesConstraints == null)
	    computeValueSatisfiesConstraints();
	return valueSatisfiesConstraints[valueIndex]; 
    }


    abstract public void init() throws SQLException, Exception;

    /* Given an item, the function extracts the value from the row
       (using rs.getXXXX(dbColumnIndex), and gives the index of the value */
    public int getValueIndex(Item item) throws SQLException {
	return item.getValueIndex(attributeIndex);
    }

    /* Given a current row from a ResultSet rs, the function extracts the value from the row
       (using rs.getXXXX(dbColumnIndex), and gives the index of the value */
    abstract public int getValueIndex(ResultSet rs) throws SQLException;

    /* Given a current row from a ResultSet rs, the function extracts the value from the row
       (using rs.getXXXX(dbColumnIndex), and gives the index of the value */
    abstract public int getValueIndex(ResultSet rs, int dbColumnIndex) throws SQLException;

    /*
    public String getDbValueString(int valueIndex) {
	return getDbValueString(valueIndex, true);
    }
    */

    abstract public String getDbValueString(int valueIndex, boolean quoteIfNecessary);

    public String getDbValueString(Item item, boolean quoteIfNecessary) throws SQLException {
	return getDbValueString(getValueIndex(item), quoteIfNecessary);
    }

    /* For a given valueIndex, it gets a string corresponding to the equal constraint on this value */
    public abstract String getEqualConstraintString(int valueIndex);



    protected void computeCurrentNbrCompatibleDistinctValues() throws SQLException {
	ECatalog.lowlevelMsg("EXPENSIVE: " + label + ".computeCurrentNbrCompatibleDistinctValues()");
	String query="SELECT COUNT(DISTINCT(" + id + ")) FROM " + db.fromClause + " WHERE " + db.getConstraintsClause();
	currentNbrCompatibleDistinctValues = SqlUtil.getUniqueInt(db.executeQuery(query));
    }


    /* It computes valueSatisfiesConstraints[]
     * This function requieres that db.constraints.updateContext() was called first!
     */
    private void computeValueSatisfiesConstraints() {
	ECatalog.lowlevelMsg("EXPENSIVE: " + label + ".computeValueSatisfiesConstraints()");

	//Selecte the constraints that use this attribute. TODO minor: this could be computed only once at the begining, and each time constraints are added/removed
	Vector<Constraint> cs = new Vector<Constraint>();
	for (Constraint c : db.constraints) {
	    if (!c.areDetailsDefined())
		continue;
	    if (c.doesInvolveAttribute(this))
		cs.add(c);
	}

	valueSatisfiesConstraints = new boolean[nbrDistinctValues];
	for (int valueIndex = 0; valueIndex < nbrDistinctValues; valueIndex++)
	    valueSatisfiesConstraints[valueIndex] = computeValueSatisfiesConstraints(cs, valueIndex);
    }

    /* This call is expensive, and it is called once by updateConstraintsContext.
     * This info is later available at valueSatisfiesConstraints 
     * This function requieres that db.constraints.updateContext() was called first!
     */
    private boolean computeValueSatisfiesConstraints(Vector<Constraint> cs, int valueIndex) {
	for (Constraint c : cs) {
	    if (!c.doesAttributeValueSatisfyConstraint(this, valueIndex))
		return false;
	}
	return true;
    }
}

