/*******************************************************************************
 * 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.dicom.gui;

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;

import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFileChooser;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.SwingConstants;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.table.TableCellRenderer;
import javax.swing.tree.TreePath;

import lu.tudor.santec.dicom.gui.DICOMSettingsPlugin;
import lu.tudor.santec.dicom.gui.DicomFileDialog;
import lu.tudor.santec.gecamed.core.gui.GECAMedColors;
import lu.tudor.santec.gecamed.core.gui.GECAMedFonts;
import lu.tudor.santec.gecamed.core.gui.GECAMedIconNames;
import lu.tudor.santec.gecamed.core.gui.GECAMedMessage;
import lu.tudor.santec.gecamed.core.gui.GECAMedMessageListener;
import lu.tudor.santec.gecamed.core.gui.GECAMedModule;
import lu.tudor.santec.gecamed.core.gui.IconFetcher;
import lu.tudor.santec.gecamed.core.gui.MainFrame;
import lu.tudor.santec.gecamed.core.gui.RegistrationDesk;
import lu.tudor.santec.gecamed.core.gui.listener.EntryTypeRegister;
import lu.tudor.santec.gecamed.core.gui.listener.IEntryPrintRenderer;
import lu.tudor.santec.gecamed.core.gui.listener.IEntryTypeHandler;
import lu.tudor.santec.gecamed.core.gui.utils.LineColorCellRenderer;
import lu.tudor.santec.gecamed.core.gui.widgets.ErrorDialog;
import lu.tudor.santec.gecamed.core.gui.widgets.HeaderedPanel;
import lu.tudor.santec.gecamed.core.utils.FileUtils;
import lu.tudor.santec.gecamed.core.utils.ManagerFactory;
import lu.tudor.santec.gecamed.dicom.ejb.entity.beans.DCMEntry;
import lu.tudor.santec.gecamed.dicom.ejb.entity.beans.DCMImage;
import lu.tudor.santec.gecamed.dicom.ejb.entity.beans.DCMSeries;
import lu.tudor.santec.gecamed.dicom.ejb.entity.beans.DCMStudy;
import lu.tudor.santec.gecamed.dicom.ejb.session.beans.DCMManagerBean;
import lu.tudor.santec.gecamed.dicom.ejb.session.interfaces.DCMManagerInterface;
import lu.tudor.santec.gecamed.patient.ejb.entity.beans.IncidentEntry;
import lu.tudor.santec.gecamed.patient.ejb.entity.beans.Patient;
import lu.tudor.santec.gecamed.patient.ejb.session.beans.IncidentManagerBean;
import lu.tudor.santec.gecamed.patient.ejb.session.interfaces.IncidentManager;
import lu.tudor.santec.gecamed.patient.gui.PatientManagerModule;
import lu.tudor.santec.gecamed.patient.gui.PatientViewTab;
import lu.tudor.santec.i18n.Translatrix;

import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.jdesktop.swingx.JXTreeTable;
import org.jdesktop.swingx.decorator.HighlighterFactory;

import com.jgoodies.forms.layout.CellConstraints;
import com.jgoodies.forms.layout.FormLayout;


/**
 * PatientViewTab that shows the dicom hsitory of the current patient.
 * 
 *
 * @author Johannes Hermen johannes.hermen(at)tudor.lu
 *
 * @version
 * <br>$Log: PatientDicomPanel.java,v $
 * <br>Revision 1.28  2013-12-27 18:09:23  donak
 * <br>Cleanup of imports
 * <br>
 * <br>Revision 1.27  2013-07-15 06:18:35  ferring
 * <br>logging changed
 * <br>
 * <br>Revision 1.26  2013-06-27 13:40:23  ferring
 * <br>dicom viewer updated
 * <br>
 * <br>Revision 1.25  2013-02-05 13:15:18  ferring
 * <br>letter status added
 * <br>
 * <br>Revision 1.24  2012-01-26 13:42:43  troth
 * <br>Add tooltips to the buttons.
 * <br>
 * <br>Revision 1.23  2010-03-12 14:17:42  hermen
 * <br>cleanup of panel layouts and icons
 * <br>
 * <br>Revision 1.22  2009-05-06 15:58:51  heinemann
 * <br>added method to generate printable output of the incident entrys
 * <br>
 * <br>Revision 1.21  2008-09-25 09:43:07  heinemann
 * <br>fixed copyrights
 * <br>
 * <br>Revision 1.20  2008-09-18 14:39:17  hermen
 * <br>*** empty log message ***
 * <br>
 * <br>Revision 1.19  2008-09-15 10:07:23  hermen
 * <br>fixed import status dialog
 * <br>
 * <br>Revision 1.18  2008-07-14 12:34:37  hermen
 * <br>fixed import
 * <br>
 * <br>Revision 1.17  2008-07-10 10:14:48  hermen
 * <br>added deletion of dicom incident entries
 * <br>
 * <br>Revision 1.16  2008-07-03 11:59:16  heinemann
 * <br>*** empty log message ***
 * <br>
 * <br>Revision 1.15  2008-04-09 12:38:23  hermen
 * <br>fixed icons and translations
 * <br>
 * <br>Revision 1.14  2008-04-09 09:39:43  heinemann
 * <br>*** empty log message ***
 * <br>
 * <br>Revision 1.13  2008-04-08 14:33:52  hermen
 * <br>added comments
 * <br>
 * <br>Revision 1.12  2008-04-08 13:15:32  hermen
 * <br>added dicom entry to medical history
 * <br>
 * <br>Revision 1.11  2008-04-03 14:14:22  hermen
 * <br>fixed image loading
 * <br>
 * <br>Revision 1.10  2008-03-28 14:12:20  hermen
 * <br>changed file path handling to new ServerConfiguration and FileUtils classes
 * <br>
 * <br>Revision 1.9  2008-03-12 14:53:50  hermen
 * <br>*** empty log message ***
 * <br>
 * <br>Revision 1.8  2008-03-12 10:30:06  hermen
 * <br>changed PatientViewTab to abstract and added getName() method
 * <br>
 * <br>Revision 1.7  2008-03-11 15:23:25  hermen
 * <br>small bugfix
 * <br>
 * <br>Revision 1.6  2008-03-05 07:27:39  hermen
 * <br>a lot of improvements and bugfixes
 * <br>
 * <br>Revision 1.5  2008-02-29 08:44:01  hermen
 * <br>update and expand tree
 * <br>
 * <br>Revision 1.4  2008-02-27 09:15:11  hermen
 * <br>removed debugging
 * <br>
 * <br>Revision 1.2  2008-02-27 08:33:43  hermen
 * <br>new with treetablemodel
 * <br>
 * <br>Revision 1.1  2008-02-26 10:45:51  hermen
 * <br>initial checkin of the dicom module
 * <br>
 *
 */
public class PatientDicomPanel extends PatientViewTab implements ActionListener, TreeSelectionListener, GECAMedMessageListener,IEntryTypeHandler
{
    //~ Static fields/initializers =============================================

    public static final String NAME = "DICOM_PANEL";
	
	public static final String SELECT_STUDY = "SELECT_STUDY";
	
	
	/**
	 * static logger for this class
	 */
	private static Logger logger = Logger.getLogger(PatientDicomPanel.class
			.getName());
	
    private static final long serialVersionUID = 1L;
    private static final String LINESPACE = "1dlu"; 
    
    // USED ICONS
	public static final String ICON_DCM = "dcm.png";
	public static final String ICON_DICOM = "dicom.png";
	public static final String ICON_ADD_FILES = "open.png";
	public static final String ICON_PROGRESS = "progress.png";
	public static final String ICON_INFO = "info.png";
	public static final String ICON_DONE = "done.png";
	public static final String ICON_WARN = "messagebox_warning.png";
	
	public static final String ICON_STUDY = "study.png";
	public static final String ICON_SERIES = "series.png";
	public static final String ICON_IMAGE = "image.png";
	
	public static final int TREE_WIDTH = 300;
	public static final int PREVIEW_WIDTH = 60;

	
    //~ Instance fields ========================================================

	private Collection<JComponent> actionComponents = new ArrayList<JComponent>();

	private static DicomFileDialog dicomFileDialog;
	
	private static DCMImageDialog dcmImageDialog;
	
	private static DICOMSettingsPlugin dicomsettings;

	private Patient patient;
	
	private boolean isRunning = false;

	private HeaderedPanel tablePanel;

	private JXTreeTable table;

	private JButton addImageButton;

	private DCMImportDialog dcmImportDialog;

	private DCMManagerInterface dcmManager;

	private DCMTreeTableModel dicomTableModel;

	private JPopupMenu popup;

	private MouseEvent event;

	private DCMIncidentEntryRenderer incidentRenderer;

	private IncidentManager incidentManager;

	protected LinkedList<File>	file2delete = new LinkedList<File>();

    //~ Constructors ===========================================================
    /**
     * builds a new PatientDicomPanel to show/edit Patients medical images
     */
    public PatientDicomPanel()
    {
    	
    	// load translations
    	Translatrix.addBundle("lu.tudor.santec.gecamed.dicom.gui.resources.Translatrix");
    	    	
    	this.setOpaque(false);
    	this.setTitle(Translatrix.getTranslationString("dcm.dcm"));
    	this.setIcon(IconFetcher.getIcon(this.getClass(), ICON_DCM));

    	dcmImportDialog = new DCMImportDialog();
    	
    	// build the Panel
        this.buildPanel();

        if (dicomsettings == null) {
        	dicomsettings = new DICOMSettingsPlugin("DCM_SETTINGS", false, true, false, false, false);
        	PatientManagerModule.getInstance().addSettingsPlugin(dicomsettings);
        }
        
        	
        if (dicomFileDialog == null) {
        	try {
        		dicomFileDialog = new DicomFileDialog(
        				MainFrame.getInstance(),
        				MainFrame.getInstance().settingsPanel,
        				dicomsettings);				
			} catch (Exception e) {
				logger.log(Level.WARN, "Error creating DicomFileDialog: check settings" , e);
			}
        }
        
        if (dcmImageDialog == null) {
        	dcmImageDialog = new DCMImageDialog(MainFrame.getInstance());
        }

        addImageButton = new JButton(
	        		Translatrix.getTranslationString("dcm.addFiles"), 
	        		IconFetcher.getMediumIcon(this.getClass(), ICON_ADD_FILES));
	    addImageButton.setHorizontalAlignment(SwingConstants.LEFT);
	    addImageButton.setEnabled(true);
	    addImageButton.setToolTipText(Translatrix.getTranslationString("dcm.addFilesTip"));
	    addImageButton.setIconTextGap(1);
	    addImageButton.setFont(GECAMedFonts.BUTTON_FONT);
	    addImageButton.setMargin(new java.awt.Insets(0, 0, 0, 0));
	    addImageButton.addActionListener(this);
	    this.actionComponents.add(addImageButton);
	    
		try {
 			dcmManager = (DCMManagerInterface) ManagerFactory.getRemote(DCMManagerBean.class);
 			incidentManager = (IncidentManager) ManagerFactory.getRemote(IncidentManagerBean.class);
		}	catch (Exception p_Exception) 
 		{
 			logger.warn(p_Exception.getLocalizedMessage());
 		}
		
		
 		// add listener for selections
 		RegistrationDesk.addGECAMedMessageListener(this);
 		
 		
 		// add history listener
 		EntryTypeRegister.registerHandler(DCMEntry.DCM_ENTRY_TYPE, this);
 		
 		incidentRenderer = new DCMIncidentEntryRenderer();
		
    }

    //~ Methods ================================================================
    
	@Override
	public String getName() {
		return NAME;
	}
    
	/* (non-Javadoc)
	 * @see lu.tudor.santec.gecamed.patient.gui.PatientViewTab#getActionComponents()
	 */
	@Override
	public Collection<JComponent> getActionComponents() {
		return actionComponents;
	}

	/* (non-Javadoc)
	 * @see lu.tudor.santec.gecamed.core.gui.GECAMedTab#enableTab()
	 */
	@Override
	public void enableTab() {
		/* ============================================= */
		super.enableTab();
		/* ============================================= */
	}
   
	
	/* (non-Javadoc)
	 * @see lu.tudor.santec.gecamed.patient.gui.PatientViewTab#setPatient(lu.tudor.santec.gecamed.patient.ejb.entity.beans.Patient)
	 */
	public void setPatient(Patient patient) {
		this.patient = patient;
		
		for (File f : file2delete)
		{
			if (f.exists())
				f.delete();
		}
		file2delete.clear();
		
		if (this.isVisible()) {
			reloadTable();
		}
	}


	/**
     * adds the components to the panel
     */
    private void buildPanel() {
        initComponents();

        JPanel jp = new JPanel();
        jp.setBorder(BorderFactory.createEmptyBorder(4,4,4,4));
        
        // build the Layoute);
        FormLayout layout = new FormLayout("fill:pref:grow",  
                LINESPACE + ", fill:pref:grow, " + LINESPACE); 
        jp.setLayout(layout);
        CellConstraints cc = new CellConstraints();
        
        // add Panels
        jp.setOpaque(false);
               
        this.tablePanel = new HeaderedPanel();
        this.tablePanel.setLayout(new BorderLayout());
        this.tablePanel.setOpaque(false);
        this.tablePanel.setHeader(Translatrix.getTranslationString("dcm.history"));
        this.tablePanel.setHeaderIcon(IconFetcher.getMediumIcon(this.getClass(), ICON_DCM));
        
        JScrollPane pane = new JScrollPane(this.table);
        pane.setOpaque(false);
        pane.getViewport().setOpaque(false);
        this.tablePanel.add(pane, BorderLayout.CENTER);
        jp.add(this.tablePanel, cc.xy(1,2));
        
        
        this.setLayout(new BorderLayout());
        this.add(jp, BorderLayout.CENTER);
        
    }
    
    /**
     * initialises the Components
     */
    private void initComponents()
    {
    	this.dicomTableModel = new DCMTreeTableModel();
    	this.table = new JXTreeTable();
    	this.table.setTreeTableModel(this.dicomTableModel);
    	this.table.setRootVisible(false);
    	this.table.setTreeCellRenderer(new DCMTreeCellRenderer());
    	this.table.setRowHeight(34);
    	this.table.getTableHeader().setReorderingAllowed(false);
    	this.table.addTreeSelectionListener (this);
    	this.table.setHighlighters(HighlighterFactory.createAlternateStriping(
    				GECAMedColors.c_OddLineBackground,		
    				GECAMedColors.c_EvenLineBackground 
    					));
    	
    	table.getColumnModel().getColumn(0).setMaxWidth(TREE_WIDTH);
    	table.getColumnModel().getColumn(0).setMinWidth(TREE_WIDTH);
    	table.getColumnModel().getColumn(0).setPreferredWidth(TREE_WIDTH);
    	
    	table.getColumnModel().getColumn(2).setMaxWidth(PREVIEW_WIDTH);
    	table.getColumnModel().getColumn(2).setMinWidth(PREVIEW_WIDTH);
    	table.getColumnModel().getColumn(2).setPreferredWidth(PREVIEW_WIDTH);

		// add a listener to get table clicks
		table.addMouseListener(
				new MouseAdapter() {

					public void mouseClicked(MouseEvent e) {
						/* ============================================= */
						// get the current row
						int row = table.rowAtPoint(e.getPoint());
						// doubleclick --> open
						if (e.getClickCount() >= 2) {
							TreePath path = table.getPathForRow(row);
							DCMEntry entry = (DCMEntry) path.getLastPathComponent();
							if (DCMEntry.SERIES == entry.getEntryType()) {
								openImage((DCMSeries) entry);
							}							
						} 
						/* ============================================= */
					}

					/* (non-Javadoc)
					 * @see java.awt.event.MouseAdapter#mouseReleased(java.awt.event.MouseEvent)
					 */
					@Override
					public void mouseReleased(MouseEvent e) {
						if (e.isPopupTrigger()) {
							showMenu(e);
						}
					}
					
					/* (non-Javadoc)
					 * @see java.awt.event.MouseAdapter#mousePressed(java.awt.event.MouseEvent)
					 */
					@Override
					public void mousePressed(MouseEvent e) {
						if (e.isPopupTrigger()) {
							showMenu(e);
						}
					}
				});
    }
    
	
	/**
	 * show a menu on right click
	* @param c
	 * @param x
	 * @param y
	 */
	private void showMenu(MouseEvent e) {
		this.event = e;
		if (popup == null) {
			popup = new JPopupMenu();
			popup.add(new AbstractAction(
						Translatrix.getTranslationString("core.delete") + " " +
						Translatrix.getTranslationString("dcm.study") + "/" + 
						Translatrix.getTranslationString("dcm.series"),
					IconFetcher.getSmallIcon(GECAMedModule.class, GECAMedIconNames.REMOVE_LINE)) {
				private static final long serialVersionUID = 1L;
				public void actionPerformed(ActionEvent ae) {
					//	get the current row
					int row = table.rowAtPoint(event.getPoint());
					table.setRowSelectionInterval(row, row);
					TreePath path = table.getPathForRow(row);
					DCMEntry entry = (DCMEntry) path.getLastPathComponent();
					try {
						if (DCMEntry.STUDY == entry.getEntryType()) {
						    DCMStudy study = (DCMStudy)entry;
						    Collection<DCMSeries> series = dcmManager.getSeries(study.getId());
						    for (Iterator<DCMSeries> iter = series.iterator(); iter.hasNext();) {
							DCMSeries serie = (DCMSeries) iter.next();
							if (serie.getIncidentEntryID() != null) {
							    incidentManager.removeIncidentEntry(serie.getIncidentEntryID());
							}
						    }
						    dcmManager.deleteStudy(study);
						    if (study.getIncidentEntryID() != null) {
							incidentManager.removeIncidentEntry(study.getIncidentEntryID());
						    }
						}	else if (DCMEntry.SERIES == entry.getEntryType()) {
							DCMSeries series = (DCMSeries)entry;
						        dcmManager.deleteSeries(series);
							if (series.getIncidentEntryID() != null) {
							    incidentManager.removeIncidentEntry(series.getIncidentEntryID());
							}
						}	
					} catch (Exception e) {	
						e.printStackTrace();
					}
					PatientManagerModule.getInstance().getPatientPanel().reloadHistory();
					reloadTable();
				}
			});
		}
		int row = table.rowAtPoint(event.getPoint());
		if (row < 0) 
			return;
		table.setRowSelectionInterval(row, row);
		popup.show(e.getComponent(), e.getX(), e.getY());
	}

	/**
	 * opens the images from the provided DCMSeries
	 * @param series the provided DCMSeries
	 */
	public void openImage(final DCMSeries series) {
		if (isRunning)
			return;

		new Thread() {
			public void run() {
				try {
					isRunning = true;
					MainFrame.getInstance().setWaitCursor(true);
					Collection<DCMImage> images = dcmManager.getImages(series.getId());
					if (images == null) {
						logger.warn("ERROR getting Image for ID: "
								+ series);
					} else {
						Collection<File> imgBytes = new ArrayList<File>();
						File dcmFile;
						DCMImage dcmImage;
						for (Iterator<DCMImage> iter = images.iterator(); iter
								.hasNext();) {
							dcmImage = (DCMImage) iter.next();
							dcmFile = File.createTempFile("gecamed_dicom_temp_" + dcmImage.getInstanceUID(), ".dcm");
							dcmFile.deleteOnExit();
							file2delete.add(dcmFile);
							FileUtils.writeFile(dcmManager.getImageFile(dcmImage), dcmFile);
							imgBytes.add(dcmFile);
						}
						dcmImageDialog.showImages(imgBytes.toArray(new File[imgBytes.size()]));
						
					}
				} catch (Exception e1) {
					ErrorDialog.showErrorDialog(
							MainFrame.getInstance(), 
							Translatrix.getTranslationString("dcm.imageError"), 
							Translatrix.getTranslationString("dcm.imageErrorText"), 
							"");
					e1.printStackTrace();
				}
				MainFrame.getInstance().setWaitCursor(false);
				isRunning = false;
			}
		}.start();
	}
	
	
	/* (non-Javadoc)
	 * @see lu.tudor.santec.gecamed.core.gui.GECAMedTab#preparetoShowup()
	 */
	@Override
	public void preparetoShowup() {
		if (! this.patient.equals(dicomTableModel.getPatient())) {
			reloadTable();
		}
	}

	/* (non-Javadoc)
	 * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
	 */
	public void actionPerformed(ActionEvent e) {
		if (e.getSource().equals(this.addImageButton)) {
			PatientManagerModule.getInstance().getPatientPanel().showPanel(this.getName());
			addImages();
		}
	}

	/**
	 * add new images to the patient record using the dicom 
	 * selector dialog
	 */
	private void addImages() {
		int retval = dicomFileDialog.showDialog();

		File[] files = new File[1];
		
		if (retval == JFileChooser.APPROVE_OPTION) {
			if (dicomFileDialog.getSingleFileSelected()) {
				files[0] = dicomFileDialog.getSelectedFile();
			} else {
				files = dicomFileDialog.getSelectedFiles();
			}
			dcmImportDialog.importFiles(files, patient, this);
			// reload dicom history
			reloadTable();
			// reload patient's history
			PatientManagerModule.getInstance()
		    	.getPatientPanel().reloadHistory();
		}
	}
	
	/**
	 * reload the treetable for the new patient
	 */
	protected void reloadTable() {
		this.dicomTableModel = new DCMTreeTableModel();
		this.dicomTableModel.setPatient(patient);
		this.table.setTreeTableModel(this.dicomTableModel);
		// set the table width
        	table.getColumnModel().getColumn(0).setMaxWidth(TREE_WIDTH);
        	table.getColumnModel().getColumn(0).setMinWidth(TREE_WIDTH);
        	table.getColumnModel().getColumn(0).setPreferredWidth(TREE_WIDTH);
        	table.getColumnModel().getColumn(2).setMaxWidth(PREVIEW_WIDTH);
        	table.getColumnModel().getColumn(2).setMinWidth(PREVIEW_WIDTH);
        	table.getColumnModel().getColumn(2).setPreferredWidth(PREVIEW_WIDTH);
        	
        	// set the selection modes
        	table.getSelectionModel().setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        	table.setColumnSelectionAllowed(false);
        	
        	// expand the tree
        	table.expandAll();
		dcmImageDialog.clear();
	}

	public void valueChanged(TreeSelectionEvent e) {
//		System.out.println("select element: " + e);
	}
	
	/**
	 * selects the specified series (and opens it)
	 * @param series
	 * @param openSeries
	 */
	public void selectSeries(DCMSeries series, boolean openSeries) {
		PatientManagerModule.getInstance().getPatientPanel().showPanel(this.getName());
		this.table.expandAll();
		int rows = this.table.getRowCount();
		for (int i = 0; i < rows; i++) {
			TreePath path = table.getPathForRow(i);
			DCMEntry entry = (DCMEntry) path.getLastPathComponent();
			if (entry.equals(series)) {
				table.setRowSelectionInterval(i, i);
				if (openSeries) {
					openImage(series);
				}
				return;
			}
		}
	}
	
	/**
	 * selects the specified study
	 * @param study
	 */
	public void selectStudy(DCMStudy study) {
		PatientManagerModule.getInstance().getPatientPanel().showPanel(this.getName());
		this.table.expandAll();
		int rows = this.table.getRowCount();
		for (int i = 0; i < rows; i++) {
			TreePath path = table.getPathForRow(i);
			DCMEntry entry = (DCMEntry) path.getLastPathComponent();
			if (entry.equals(study)) {
				table.setRowSelectionInterval(i, i);
				return;
			}
		}
	}
	
	/**
	 * selects the specified series (and opens it)
	 * @param series
	 * @param openSeries
	 */
	public void selectSeriesByIncidentEntry(IncidentEntry iEntry, boolean openSeries) {
		PatientManagerModule.getInstance().getPatientPanel().showPanel(this.getName());
		this.table.expandAll();
		int rows = this.table.getRowCount();
		for (int i = 0; i < rows; i++) {
			TreePath path = table.getPathForRow(i);
			DCMEntry entry = (DCMEntry) path.getLastPathComponent();
			if (iEntry.getId().equals(entry.getIncidentEntryID())) {
				table.setRowSelectionInterval(i, i);
				if (openSeries && entry instanceof DCMSeries) {
					openImage((DCMSeries) entry);
				}
				return;
			}
		}
	}

	public void handleGECAMedMessage(GECAMedMessage message) {
		if (message.getModul() instanceof PatientManagerModule) {
    		if (message.getMessage().equals(PatientDicomPanel.SELECT_STUDY)) {
    			try {
    				DCMStudy study = (DCMStudy) message.getNewValue();
    				selectStudy(study);					
				} catch (Exception e) {
					logger.warn("Error selecting Study for message: " + message);
				}
    			}	
		}
	}
	
	public boolean openEntry(IncidentEntry entry) {
	    this.selectSeriesByIncidentEntry(entry, false);
	    return true;
	}

	public Collection<Action> getActions(IncidentEntry entry) {
	    return null;
	}
	
	public JPopupMenu getPopup(IncidentEntry entry)
	{
		return null;
	}

	public TableCellRenderer getRenderer(String entryType) {
	    return incidentRenderer;
	}

	public HashMap<Integer, Object> getSpecialEntries(String entryType, Integer patientId) {
	    return null;
	}
	
	
	class DCMIncidentEntryRenderer extends LineColorCellRenderer {

		private static final long serialVersionUID = 1L;
		
		private final static int fontSize = 9;
		
		private final String ICON = this.getClass().getResource("resources/icons/"+PatientDicomPanel.ICON_SERIES).toString();
		
		/*
		 * (non-Javadoc)
		 * 
		 * @see lu.tudor.santec.gecamed.core.gui.utils.LineColorCellRenderer#getTableCellRendererComponent(javax.swing.JTable,
		 *      java.lang.Object, boolean, boolean, int, int)
		 */
		@Override
		public Component getTableCellRendererComponent(JTable p_Table, Object value, boolean p_IsSelected, boolean hasFocus, int p_Row, int p_Column) {
			/* ====================================================== */
			if (value instanceof IncidentEntry) {
				/* ------------------------------------------------------- */
				IncidentEntry entry = (IncidentEntry) value;
//				IncidentEntryType type = entry.getEntryType();
				// type name
				if (p_Column == 2) {
					/* ------------------------------------------------------- */
					return super.getTableCellRendererComponent(p_Table, "Im", p_IsSelected,
							hasFocus, p_Row, p_Column);
					/* ------------------------------------------------------- */
				} else
					if (p_Column == 3) {
						/* ------------------------------------------------------- */
						StringBuffer buff  = new StringBuffer("<html><span style=\"font-family:Arial;font-size:"
																+ fontSize + "px;\">");
						buff.append("<table border=\"0\"><tr vAlign=\"top\"><td>");
						/* ------------------------------------------------------- */
						// create the icon
						/* ------------------------------------------------------- */
						buff.append("<img src=\""+ICON+"\" width=\"24\" height=\"24\"></td><td>");
						/* ------------------------------------------------------- */
						// add the text
						/* ------------------------------------------------------- */
						if (entry.getTextContent() != null)
							buff.append(entry.getTextContent()+"<br>");
						return super.getTableCellRendererComponent(p_Table, buff.toString(), p_IsSelected,
								hasFocus, p_Row, p_Column);
						/* ------------------------------------------------------- */
					}
				/* ------------------------------------------------------- */
			}
			return super.getTableCellRendererComponent(p_Table, value, p_IsSelected,
					hasFocus, p_Row, p_Column);
			/* ====================================================== */
		}
	}


	public IEntryPrintRenderer getPrintRenderer(String entryType) {
		/* ====================================================== */
		// TODO Auto-generated method stub
		return null;
		/* ====================================================== */
	}
	
}
