/*
 * 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 external;

import ecatalog.ECatalog;
import ecatalog.gui.MainGui;
import ecatalog.db.Database;
import ecatalog.db.Attribute;
import ecatalog.db.BooleanAttribute;
import ecatalog.db.Item;

import ecatalog.gui.visualization.ECatalogItemTableRenderer;
import utils.itemTable.*;
import utils.ComponentTableCellRenderer;

import dpc.utils.DebugUtil;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.table.*;
import javax.swing.border.*;
import java.util.Vector;
import java.sql.*;

import java.awt.Color;
import javax.swing.table.TableCellRenderer;


/* The class concerned with the table rendering */
public class CarItemTableRenderer extends ECatalogItemTableRenderer {
    int[][] rowColumnsIndex = {{0, 2, 3, 4, 5, 6, 7, 8}, {9, 10, 11, 12, 13, 14, 15, 16}};
    int[] rowFeaturesIndex = {17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35};
    int modelColumnWidth = 200;

    Database db;
    ImageIcon[][] icons;
    //String imagesSuffixes[] = {"_yes_sat", "_yes_notsat", "_no_sat", "_no_notsat"};
    String imagesSuffixes[] = {"_yes_sat", "_yes_notsat", "_no_sat", "_yes_notsat"};

    //ImageIcon nullIcon, emptyIcon;
    FeaturesItemTableCellRenderer featuresItemTableCellRenderer;

    public void init(Database db) {
	this.db = db;
	icons = new ImageIcon[rowFeaturesIndex.length][imagesSuffixes.length];
	for (int i = 0; i < rowFeaturesIndex.length; i++) {
	    for (int suffixIndex = 0; suffixIndex < imagesSuffixes.length; suffixIndex++) {
		String fileName = "images/features/" + db.getAttribute(rowFeaturesIndex[i]).getId() + imagesSuffixes[suffixIndex] + ".gif";
		ECatalog.lowlevelMsg("LOADING IMAGE: " + fileName);
		icons[i][suffixIndex] = new ImageIcon(fileName);
	    }
	}
	//emptyIcon = new ImageIcon("images/features/empty.gif");
	//nullIcon = new ImageIcon("images/features/null.gif");

	featuresItemTableCellRenderer = new FeaturesItemTableCellRenderer();
    }


    /* Get the number of columns */
    public int getNbrColumns() {
	return rowColumnsIndex[0].length; 
    }
    /* Get the number of rows for each item */
    public int getNbrItemRows() {
	return 3;
    }

    /* Get the column name
     * @param itemRow  the row index (not the table row, but the item row)
     * @param tableCol  the column index
     */
    public String getColumnName(int itemRow, int tableCol) {
	if (itemRow != 2)
	    return db.getAttribute(rowColumnsIndex[itemRow][tableCol]).getConfig().getLabel();
	else
	    return "Other features";
    }


    /* Get the cell which will be rendered, given itemRow and tableCol
     * @param itemRow  the row index (not the table row, but the item row)
     * @param tableCol  the column index
     * @retrun the cell to be used. (change [int,int] by a class width itemRow and tableCol attributes)
     */
    public CellIndex getVisibleCell(int itemRow, int tableCol) {
	if (itemRow == 2)
	    return new CellIndex(2, 0);
	return new CellIndex(itemRow, tableCol);
    }


    /* Get the horizontal and vertical span
     * @param itemRow  the row index (not the table row, but the item row)
     * @param tableCol  the column index
     */
    public CellSpan getCellSpan(int itemRow, int tableCol) {
	if (itemRow == 2 && tableCol == 0)
	    return new CellSpan(rowColumnsIndex[0].length, 1);
	return new CellSpan(1,1);

    }

    /* Get the cell size
     * @param itemRow   the row index (not the table row, but the item row)
     * @param tableCol  the column index
     * @result          the size for the specified cell.
     cellSize.width == -1 means no width preference (use default)
     cellSize.height == -1 means no height preference (use default)
     cellSize == null means no width nor height preference (use default)
    */
    public CellSize getCellSize(int itemRow, int tableCol) {
	if (itemRow == 2) {
	    int itemRowHeight = icons[0][0].getIconHeight() + 3; //panel insets
	    return new CellSize(-1, itemRowHeight);
	} else if (tableCol == 1) {
	    int columnWidth = modelColumnWidth;
	    return new CellSize(columnWidth, -1);
	}

	return null;
    }


    /* the class implementing this interface should know to extract the information from the Item 
     * @param item      the item from where to extract the requested information
     * @param itemRow   the row index (not the table row, but the item row)
     * @param tableCol  the column index
     */
    public Object getValueAt(Object item, int itemRow, int itemColumn) {
	try {
	    //if (itemRow == 1 && itemColumn == 7)  //TODO: to remove...
	    //	return "rank:" + ecatalog.db.DBRank.computeItemRank(db, (Item)item);

	    if (itemRow != 2) {
		int attributeIndex = rowColumnsIndex[itemRow][itemColumn];
		Attribute at = db.getAttribute(attributeIndex);
		return at.getValueString(at.getValueIndex((Item)item));
	    } else {
		return item;  //return the whole item itself, it will be used to create the features panel
	    }
	} catch (SQLException e) { return ""; }
    }


    /* gets the renderer for the specified cell 
     * @param itemRow  the row index (not the table row, but the item row)
     * @param tableCol  the column index
     * @result a renderer for this cell, or null if non specified (in this case, the default one should be used)
     */
    public ItemTableCellRenderer getItemTableCellRenderer(int itemIndex, int itemRow, int tableCol) {
	if (itemRow == 2)
	    return featuresItemTableCellRenderer;
	return null;
    }


    /* Returns true if the items can be sorted using this attribute.
     * If so, and the user ask to sort, sortBy will be called
     */
    public boolean isSortableByAttribute(int attributeIndex) {
	return true;
    }

    /* Return the attribute index associated to the cell specified by itemRow,tableCol.
     * @param itemRow  the row index (not the table row, but the item row)
     * @param tableCol  the column index

     * @ result         the attribute index associated to the cell specified by itemRow,tableCol.
     *                  If that cell is not associated to any attribute, return -1
     */
    public int getItemAttributeIndex(int itemRow, int tableCol) {
	if (itemRow != 2)
	    return rowColumnsIndex[itemRow][tableCol];
	return -1;
    }


    /* returns whether the attribute is satisfied by the constraints given by the user 
     * ignoring the database
     */
    public boolean isCellSatisfied(Item item, int itemRow, int tableCol) {
	try {
	    if (itemRow != 2) {
		int attributeIndex = rowColumnsIndex[itemRow][tableCol];
		Attribute at = db.getAttribute(attributeIndex);
		
		if (attributeIndex == 2) {  //Type is displayed, but Model is not displayed. 
		                            //If model is not satisfied, display Type as not satisfied neither
		    Attribute atModel = db.getAttribute(1);
		    return (at.getValueSatisfiesConstraints(item.getValueIndex(attributeIndex))
			    && atModel.getValueSatisfiesConstraints(item.getValueIndex(1)));
		} else {
		    return at.getValueSatisfiesConstraints(item.getValueIndex(attributeIndex));
		}
	    } else {
		return true;
	    }
	} 
	catch (SQLException e) { throw new Error(e); }
	catch (java.lang.ArrayIndexOutOfBoundsException e) {
	    DebugUtil.printTrace("item: " + item + ", itemRow: " + itemRow + ", tableCol: " + tableCol);
	    throw e;
	}
    }

    class FeaturesItemTableCellRenderer implements ItemTableCellRenderer {
	FeaturesPanel featuresPanel = new FeaturesPanel();
	public Component getItemTableCellRendererComponent(ItemTable table, Object value, boolean isSelected, boolean hasFocus, 
							   int itemIndex, int itemRow, int tableCol) {
	    try {
		Item item = (Item) value;
		featuresPanel.update(item);
		return featuresPanel;
	    } catch (SQLException e) {
		throw new Error(e);
	    }
	}

	class FeaturesPanel extends JPanel {
	    IconLabel[] iconLabels;
	    FeaturesPanel() {
		setToolTipText("...");
		setBackground(Color.white);
		setLayout(new BoxLayout(this, BoxLayout.X_AXIS));
		setBorder(new EmptyBorder(1,3,2,3));

		iconLabels = new IconLabel[rowFeaturesIndex.length];
		for (int i = 0; i < rowFeaturesIndex.length; i++) {
		    iconLabels[i] = new IconLabel(i, icons[i]);
		    add(iconLabels[i]);
		    add(Box.createHorizontalStrut(3));
		}
	    }

	    void update(Item item) throws SQLException {
		for (int i = 0; i < rowFeaturesIndex.length; i++)
		    iconLabels[i].update(item);
	    }

	    public JToolTip createToolTip() { return MainGui.createToolTip(); }
	    public String getToolTipText(MouseEvent event) {
		//Component c = getComponentAt(event.getX(), event.getY()); //it does not work, it always return null :-?
	    
		//TODO minor: based that all icons have the same width, we can hack it. but the first way should work.
		JLabel c = getJLabelAt(this, event.getX(), event.getY());
		if (c == null)
		    return null;
		return ((JLabel)c).getToolTipText(null);
	    }

	    JLabel getJLabelAt(JPanel panel, int x, int y) {
		if (y == 0)
		    return null;
		if (y >= 1 + icons[0][0].getIconHeight())
		    return null;
		int xpos = x - 3; //the insets
		int labelWidth = icons[0][0].getIconWidth();
		int labelBoxWidth = labelWidth + 3; // the separation between labels
		int labelIndex = xpos / labelBoxWidth;
		if (labelIndex >= rowFeaturesIndex.length)
		    return null;
		if (xpos - labelIndex*labelBoxWidth >= labelWidth)
		    return null;
		return (JLabel)panel.getComponent(labelIndex*2);
	    }

	    class IconLabel extends JLabel {
		int featureIndex;
		int attributeIndex;
		BooleanAttribute at;
		ImageIcon[] icons;

		boolean value;
		boolean satisfied;

		IconLabel(int featureIndex, ImageIcon[] icons) {
		    super(icons[2]);
		    this.featureIndex = featureIndex;
		    attributeIndex = rowFeaturesIndex[featureIndex];
		    at = (BooleanAttribute)db.getAttribute(attributeIndex);

		    this.icons = icons;
		    setToolTipText("...");
		}
		void update(Item item) throws SQLException {
		    int valueIndex = item.getValueIndex(attributeIndex);
		    value = at.getValueId(valueIndex);
		    satisfied = at.getValueSatisfiesConstraints(valueIndex);

		    int iconTypeIndex = ((value == true) ? 0 : 2) + ((satisfied == true) ? 0 : 1);
		    setIcon(icons[iconTypeIndex]);
		}

		public JToolTip createToolTip() { return MainGui.createToolTip(); }
		public String getToolTipText(MouseEvent event) {
		    String text = "This car has ";
		    if (value == false)
			text += "not ";
		    text += db.getAttribute(rowFeaturesIndex[featureIndex]).getLabel();
		    if (!satisfied)
			text += ", and so it does not satisfy your criteria";
		    return text;
		}
	    }
	}
    }
}



