/*******************************************************************************
 * This file is part of GECAMed.
 * 
 * GECAMed is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License (L-GPL) as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * GECAMed 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 Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public License (L-GPL)
 * along with GECAMed.  If not, see <http://www.gnu.org/licenses/>.
 * 
 * GECAMed is Copyrighted by the Centre de Recherche Public Henri Tudor (http://www.tudor.lu)
 * (c) CRP Henri Tudor, Luxembourg, 2008
 *******************************************************************************/
package lu.tudor.santec.gecamed.core.gui.utils;

import java.awt.Component;
import java.awt.Dimension;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

import javax.swing.AbstractCellEditor;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.table.TableCellEditor;
import javax.swing.text.BadLocationException;

import lu.tudor.santec.gecamed.core.gui.GECAMedFonts;

/**
 * A TableCellEditor that allows to enter 
 * multiple lines.
 * It uses a JTextArea as editor component.
 * 
 * Use it in compination with the MultiLineCellRenderer
 * 
 * Be sure, that your JTable has setSurrendersFocusOnKeystroke(true); set.
 * 
 * 
 * @author martin.heinemann@tudor.lu
 *
 *
 * @version
 * <br>$Log: MultiLineCellEditor.java,v $
 * <br>Revision 1.3  2008-09-25 09:43:07  heinemann
 * <br>fixed copyrights
 * <br>
 * <br>Revision 1.2  2007/03/02 08:28:39  hermen
 * <br>initial checkin after the merge of PatientModuleRebuild with the main HEAD
 * <br>
 * <br>Revision 1.1.2.1  2007/01/05 13:12:34  heinemann
 * <br>allergy table comments now have a multiline editor
 * <br>
 */
public class MultiLineCellEditor   extends AbstractCellEditor implements TableCellEditor, DocumentListener{

	private static final long serialVersionUID = 1L;
//	private JTextField shortcutEditor = new JTextField();
	private JTextArea descriptionEditor = new JTextArea();
//	private JTextComponent current;
	private JTable table;
	private int rowIndex;
	
	private int rows = 0;
	
	
	/**
	 * The offset each text line needs to be displayed properly 
	 */
	private final int OFFSET = 15;
	
	public MultiLineCellEditor() {
		descriptionEditor.setPreferredSize(new Dimension(200, 30));
		descriptionEditor.setLineWrap(true);
		descriptionEditor.setFont(GECAMedFonts.TEXTFIELD_FONT);
		descriptionEditor.addKeyListener(new KeyAdapter() {
			@Override
			public void keyReleased(KeyEvent e) {
				if (e.getKeyCode() == KeyEvent.VK_TAB) {
					fireEditingStopped();
				}
			}
		});
		
		descriptionEditor.getDocument().addDocumentListener(this);
	}
	
	public Object getCellEditorValue() {
		return descriptionEditor.getText();
	}

    public Component getTableCellEditorComponent(JTable table, Object value,
            boolean isSelected, int rowIndex, int colIndex )  {
 	
    		this.table = table;
    		this.rowIndex = rowIndex;

        	descriptionEditor.setSize(table.getColumnModel().getColumn(colIndex).getWidth(),
    				descriptionEditor.getPreferredSize().height);
    		resize();
       		
    	    descriptionEditor.setText((String) value);
    	    
    	    return descriptionEditor;
    	}
    
    /* ------------------------------------------------------ */
    // helper to resize the textarea
    private void resize() {
    	/* ====================================================== */
    		try {
				rows = getLineCount(descriptionEditor);
			} catch (BadLocationException e) {
			}
    		// resize pref size
    		descriptionEditor.setPreferredSize(new Dimension(
    				descriptionEditor.getPreferredSize().width,
    				OFFSET * rows));
	    
	    if (table.getRowHeight(rowIndex) < descriptionEditor.getPreferredSize().height) {
	    	table.setRowHeight(rowIndex, descriptionEditor.getPreferredSize().height);
	      }
	    
	    
		/* ====================================================== */
    }
    

	public void changedUpdate(DocumentEvent e) {
		/* ============================================= */
		resize();
		/* ============================================= */
	}

	public void insertUpdate(DocumentEvent e) {
		/* ============================================= */
		resize();
		/* ============================================= */
	}

	public void removeUpdate(DocumentEvent e) {
		/* ============================================= */
		resize();
		/* ============================================= */
	}
	
	/** 
	  * Gibt die Anzahl der (gewrappten) Zeilen zurück. 
	  * @param area 
	  * @return 
	  * @throws BadLocationException 
	  * 
	  * @creditz <a href="http://groups.google.de/group/de.comp.lang.java/browse_thread/thread/7b2a34a94ab77fb7/400946ff25b241a4?lnk=st&q=JTextArea+getRows+&rnum=10&hl=de#400946ff25b241a4">
	  * de.comp.lang.java</a>
	  */ 
	public static int getLineCount(JTextArea area) 
	        throws BadLocationException { 
	        String text = area.getText(); 
	        int len = text.length(); 
	        int line = area.getLineOfOffset(len); 
	        return line+1; 

	}
	
	
}
