package comparingDevices;

import java.awt.Color;
import java.awt.Component;
import java.awt.FontMetrics;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Vector;
import javax.swing.BorderFactory;
import javax.swing.JCheckBox;
import javax.swing.JLabel;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.event.TableModelEvent;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableCellRenderer;

/**
 * This class represents the chart that will expose the comparison results 
 * @author MC
 *
 */
public class ComparaisonTable extends JTable{
        private static final long serialVersionUID = 1L;
	private MVC mvc;
	public ComparaisonTable(Vector vectMOC, Vector vectCompareMOC, Vector vectFileName) {
        super();
        mvc = null;
        setModel(new MyModel(vectMOC, vectCompareMOC, vectFileName));
        setDefaultRenderer(Boolean.class, new MyCellRenderer());
        setDefaultRenderer(String.class, new MyCellRenderer());
        //Allow only single a selection
        setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
             
        addMouseListener(new MouseAdapter(){

			public void mouseClicked(MouseEvent e) {
				if (e.getClickCount() == 2){
					(new MVC()).selectRow(rowAtPoint(e.getPoint()));
			    }				
			}
			});
    }
	public void setMVC(MVC mvcIn){
		mvc = mvcIn;
	}
	public ComparaisonTable(){
		super();
        setDefaultRenderer(Boolean.class, new MyCellRenderer());
        setDefaultRenderer(String.class, new MyCellRenderer());
        //Allow only single a selection
        setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        
        addMouseListener(new MouseAdapter(){

			public void mouseClicked(MouseEvent e) {
				int row = rowAtPoint(e.getPoint());
				if(row > -1){
					(mvc).selectRow(row);		
					if(e.getButton() == MouseEvent.BUTTON3){
			    	  getSelectionModel().addSelectionInterval(row,row);
			    	  (mvc).selectMenuRow(e.getPoint());
					}
				}
			}
			});
	}
	public void setData(Vector vectMOC, Vector vectCompareMOC, Vector vectFileName){
		setModel(new MyModel(vectMOC, vectCompareMOC, vectFileName));
		validate();
	}
	/**
     * getHeightCell
     * @param str
     * @param width
     * @param font
     * @return
     */
    private int getHeightCell(String str, int width, FontMetrics font)
    {
        int res = 0;
        int c;
        str = str.replaceAll("<html>","");
        str = str.replaceAll("</html>","");

        if(str != null && str != "")
        {
            String [] list = str.split(" ");

            for (int i=0; i< list.length; i++)
            {
                c = 0;
                //l = list[i].length() * charLength;
                int current = i;
                while(i < list.length && (c = c + font.stringWidth(list[i])) <= width)
                {
                    //c += l;
                    i++;
                    //l = list[i].length() * charLength;

                }
                res ++;
                if(i < list.length && i !=current)
                    i--;
            }
        }      
        return res;
    }
    public void tableChanged(TableModelEvent e) {
        super.tableChanged(e);
        int row = e.getFirstRow();
        if(row >= 0)
            resizeRow(row);          
    }
    /**
     * resizeRow
     * @param row
     */
   private void resizeRow(int row)
   {
       int max = 0;
       for( int j=0; j<getColumnCount(); j++)
           {
               // the default font
               FontMetrics font = (new JLabel()).getFontMetrics(new JLabel().getFont());
               int height = getHeightCell(getValueAt(row, j).toString(), getCellRect(row, j, true).width, font)*16;
               if(height > max)
               {
                   max = height;
                   setRowHeight(row, height);
              }
           }
   }
	    
    private class MyCellRenderer extends DefaultTableCellRenderer implements TableCellRenderer
    {
        private static final long serialVersionUID = 1L;
    	public MyCellRenderer()
        {
            super();
            //setVerticalAlignment(JLabel.NORTH);
        }
        /**
         * @see javax.swing.table.TableCellRenderer#getTableCellRendererComponent(javax.swing.JTable, java.lang.Object, boolean, boolean, int, int)
         */
        public Component getTableCellRendererComponent(JTable table,Object value,boolean isSelected,boolean hasFocus,int row,int col){
            Component c = super.getTableCellRendererComponent( table, value,isSelected,hasFocus,row,col);
            if(col != 0)
            {
                JCheckBox jCheckBox = new JCheckBox();
                jCheckBox.setHorizontalAlignment(JCheckBox.CENTER);
                jCheckBox.setBackground(c.getBackground()); 
                if(hasFocus)
                {
                	jCheckBox.setBorder(BorderFactory.createLineBorder(Color.GRAY));
                	jCheckBox.setBorderPainted(true);
                }
                if(((Boolean)value).booleanValue())
                    jCheckBox.setSelected(true);
                else
                    jCheckBox.setSelected(false);
                jCheckBox.setBackground(c.getBackground());
                c = jCheckBox;
            }
            //on grise une ligne sur 2 par soucis de visibilité
            
            if(!isSelected)
            {
	            if(row%2 != 0)
	                c.setBackground(new Color(255,255,204));
	            else
	                c.setBackground(Color.WHITE);
            }
            
            try{
            	MyModel model = (MyModel)table.getModel();
            	Boolean [] array = (Boolean[]) model.vectCompareMoc.get(row);
            	if(array[table.getColumnCount() - 1].booleanValue())
            		c.setBackground(Color.RED);
            }
            catch(Exception e){
            	//e.printStackTrace();
            }
            return c; 
        }
    }
    
    

}
