/*
 * 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 dpc.utils.TextUtil;
import dpc.utils.DebugUtil;

import java.util.*;
import java.util.regex.Pattern;
import java.sql.*;
import ecatalog.jaxb.ecatalogConfig.AttributeType;

public class TextAttribute extends Attribute {
    /* The id of all the distinct possible values */
    private String[] valuesId;

    /* The index in the array valuesId and valuesString for a given value id */
    private HashMap<String, Integer> valuesIndex;

    public TextAttribute(AttributeType config, Database db, int attributeIndex) {
	super(config, db, attributeIndex);
    }
    
    /* Computes valuesIndex, valuesId, nbrDistinctValues and valuesString */
    public void init() throws SQLException, Exception {
	getValues();
	computeValuesString();
    }

    /* Computes valuesIndex, valuesId and nbrDistinctValues */
    private void getValues() throws SQLException {
	Vector valuesIdVector = new Vector<String>();
	valuesIndex = new HashMap<String, Integer>();

	//ResultSet rs = db.executeQuery("SELECT DISTINCT(BINARY(" + id + ")) FROM " + db.fromClause + " ORDER BY " + id);
	ResultSet rs = db.executeQuery("SELECT " + id + " FROM " + db.fromClause + " WHERE " + db.whereClause + " GROUP BY " + id + " ORDER BY " + id);
	int i = 0;
	while (rs.next()) {
	    String valueId = rs.getString(1);
	    if (valueId == null) {
		ECatalog.error(new Error("Null values not accepted now"));
		throw new Error(); //it is already done, but to avoid the java compiling error
	    }
	    valuesIdVector.add(valueId);
	    valuesIndex.put(valueId, i++);
	}
	rs.close();

	nbrDistinctValues = valuesIdVector.size();
	valuesId = (String[]) valuesIdVector.toArray(new String[nbrDistinctValues]);
    }

    /* Computes valuesString */
    private void computeValuesString() throws Exception {
	String valueStringFunction = config.getValueStringFunction();
	//System.out.println("valueStringFunction: " + valueStringFunction);
	if (valueStringFunction != null) {
	    valuesString = new String[nbrDistinctValues];
	    for (int i = 0; i < valuesId.length; i++) {
		//TODO minor: after using eval, I cannot re-declare a valueId, even if I first call undeclareBean.
		//            so, the hack at the moment is to declare the valueId by heading it in the valueStringFunction
		//bsfmanager.declareBean("valueId", valuesId[i], String.class);        
		//Object result = bsfmanager.eval("javascript", "Test", 0, 0, valueStringFunction);
		//db.bsfmanager.undeclareBean("valueId");

		Object result = db.scriptEval("valueId = \"" + valuesId[i] + "\"; " + valueStringFunction);
		valuesString[i] = result.toString();
		//System.out.println("Computed for: " + valuesId[i] + ", string: " + valuesString[i]);
	    }
	} else {
	    valuesString = valuesId;
	}

    }

    public int getValueIndex(ResultSet rs) throws SQLException {
	return getValueIndex(rs, dbColumnIndex);
    }

    //TODO: there is still a strange NullPointerException of valuesIndex, when in the database there are two valuesId different only by capital letters
    //at the moment: tools/fixAccents.sh
    public int getValueIndex(ResultSet rs, int dbColumnIndex) throws SQLException {
	String valueId = rs.getString(dbColumnIndex);
	try {
	    int valueIndex = valuesIndex.get(valueId);
	    return valueIndex;
	} catch (NullPointerException e) {
	    String msg = id + ".getValueIndex NullPointerException!, valueId="+valueId + "\n" +
		id + ".getValueIndex NullPointerException!, valuesIndex="+valuesIndex;
	    ECatalog.error(new Error(msg, e));
	    throw new Error(); //it is already done, but to avoid the java compiling error
	}
    }

    static Pattern pattern = Pattern.compile("'");
    public String getDbValueString(int valueIndex, boolean quoteIfNecessary) {
	String text = valuesId[valueIndex];
	if (!quoteIfNecessary)
	    return text;

        if (text == null)
            return null;

	return "'" + pattern.matcher(text).replaceAll("''") + "'";
    }

    /* For a given valueIndex, it gets a string corresponding to the equal constraint on this value */
    public String getEqualConstraintString(int valueIndex) {
	EqualConstraint c = new EqualConstraint(this, db, new Weight(-1), null);
	c.setValueIndex(valueIndex);
	return c.getWithConstraintString();
    }
}



