/**
 *
 * @author maria
 */
package modifyIcs;

import java.awt.Color;
import java.awt.Component;
import java.awt.FontMetrics;
import javax.swing.JLabel;
import javax.swing.JTable;
import javax.swing.event.ChangeEvent;
import javax.swing.event.TableColumnModelListener;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableModel;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

/**
 * This class is the base class for ICS tables
 * @author  MC
 */
public class JTableModifyICS extends JTable implements TableModelListener, TableColumnModelListener{
	private ICSDocuments icsDocs;
    /**
	 * @uml.property  name="support"
	 */
    private static final long serialVersionUID = 1L;
    protected String[] Support;
    /**
	 * @uml.property  name="comment"
	 */
    protected String[] Comment;
    public void setICSDocs(ICSDocuments obj)
    {
        icsDocs = obj;
        
    }
    /**
     * Creates a new instance of JTableModifyICS
     */
    public JTableModifyICS(AbstractTableModel model) {
        super(model);
       
        model.addTableModelListener(this);
        //To disable reordering columns
        getTableHeader().setReorderingAllowed(false);
        setDefaultRenderer(String.class, new MyCellRenderer()); 
        Support = new String[model.getRowCount()];
        Comment = new String[model.getRowCount()];
        for(int i = 0; i < Support.length; i++)
        {
            Support[i] = (String) getValueAt(i, 4);
            Comment[i] = (String) getValueAt(i, 5);
        }
                
        for(int row = 0; row < getRowCount(); row++)
           resizeRow(row);
     
    }
    /**
     * updateModel
     * @param model
     */
    public void updateModel(DomToTableModelAdapter model)
    {
        for(int i = 0; i < Support.length; i++)
        {
            Support[i] = (String) model.getValueAt(i, 4);
            setValueAt(Support[i], i, 4);
            
            Comment[i] = (String) model.getValueAt(i, 5);
            setValueAt(Comment[i], i, 5);
        }
    }
    /**
     * 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;
    }
    /**
     * @see javax.swing.event.TableModelListener#tableChanged(javax.swing.event.TableModelEvent)
     */
    public void tableChanged(TableModelEvent e) {
        super.tableChanged(e);
        if(icsDocs != null)
        	icsDocs.fireTableModelChanged();
        int row = e.getFirstRow();
        int column = e.getColumn();
        TableModel model = (TableModel)e.getSource();
        
        if( column == 4)
        {
            Object data = model.getValueAt(row, column);
            Support[row] = data.toString();
        }
        else if ( column == 5 )
        {
        	Object data = model.getValueAt(row, column);
            Comment[row] = data.toString();
        }
        if(row >= 0)
            resizeRow(row);
          
    }
    /**
     * getDocSaved
     * @return
     */
    public Document getDocSaved()
    {
        DomToTableModelAdapter model = (DomToTableModelAdapter) getModel();
        return saveData(model.getDoc(), getSupport(), getComment());
    }
    /**
     * saveData
     * @param document
     * @param Support
     * @return
     */
     private Document saveData(Document document, String[] Support, String[] Comment)
     {
       Element racine = document.getDocumentElement();
        if(racine.hasChildNodes())
        {
            NodeList list = racine.getChildNodes();
             int k = 0;
             int l = 0;
            for(int i = 0; i < list.getLength(); i++)
            {
               
                Node raw = list.item(i);
                if(raw.getNodeType() == Node.ELEMENT_NODE)
                {
                    NodeList list2 = raw.getChildNodes();
                    for(int j = 0; j < list2.getLength(); j++)
                    {
                        Node column = list2.item(j);
                        if(column.getNodeType() == Node.ELEMENT_NODE)
                        {
                           if ( column.getNodeName() == "Support" || column.getNodeName() == "Comment" )
                           {
                        	   String value = "";
                        	   if(column.getNodeName() == "Support")
                        		   value = Support[k++];
                        	   else
                        		   value = Comment[l++];
                        		   
                               value = value.replaceAll("<html>", "");
                               value = value.replaceAll("</html>", "");
                               //column.setTextContent(value);
                               Node child = column.getFirstChild();
                               while(child != null && child.getNodeType() != Node.TEXT_NODE)
                                   child = child.getNextSibling();
                               if(child != null)
                               {
                                   child.setNodeValue(value);
                               }
                               else
                               {
                                   child = document.createTextNode(value);
                                   column.appendChild(child);
                               }	                         
                           }
                           
                        }
                    }
                    
                }                
            }
        }
       return document;
    }
     /**
      * 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);
               }
            }
    }
    /**
     * @see javax.swing.event.TableColumnModelListener#columnMarginChanged(javax.swing.event.ChangeEvent)
     */
    public void columnMarginChanged(ChangeEvent e)
    {
        super.columnMarginChanged(e);
        for(int row = 0; row < getRowCount(); row++)
           resizeRow(row);
    }
    /**
	 * getSupport
	 * @return
	 * 
	 */
    public String[] getSupport()
    {
        return Support;
    }
    /**
	 * getComment
	 * @return
	 * 
	 */
    public String[] getComment()
    {
    	return Comment;
    }
    /**
     * MyCellRenderer
     * @author MC
     *
     */
    public 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);
             //on grise une ligne sur 2 par soucis de visibilité
            if(row%2 != 0)
                c.setBackground(new Color(255,255,204));
            else
                c.setBackground(Color.WHITE);               
            return c; 
        }
       
    }
    
}
