package lu.tudor.santec.gecamed.formeditor.gui.view;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Cursor;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import javax.swing.Action;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
import javax.swing.table.TableCellRenderer;

import lu.tudor.santec.gecamed.core.ejb.entity.beans.GECAMedEntityBean;
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.GECAMedModule;
import lu.tudor.santec.gecamed.core.gui.IconFetcher;
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.widgets.GECAMedBaseDialog;
import lu.tudor.santec.gecamed.core.gui.widgets.GECAMedBaseDialogImpl;
import lu.tudor.santec.gecamed.core.utils.ManagerFactory;
import lu.tudor.santec.gecamed.formeditor.ejb.entity.beans.Form;
import lu.tudor.santec.gecamed.formeditor.ejb.entity.beans.FormTemplate;
import lu.tudor.santec.gecamed.formeditor.ejb.entity.beans.FormValue;
import lu.tudor.santec.gecamed.formeditor.ejb.session.beans.FormManagerImpl;
import lu.tudor.santec.gecamed.formeditor.ejb.session.interfaces.FormManager;
import lu.tudor.santec.gecamed.formeditor.gui.FormEditorModule;
import lu.tudor.santec.gecamed.formeditor.gui.FormIncidentEntryRenderer;
import lu.tudor.santec.gecamed.formeditor.gui.component.EditableComponent;
import lu.tudor.santec.gecamed.formeditor.gui.component.EditableSubForm;
import lu.tudor.santec.gecamed.formeditor.gui.component.FormEditorButton;
import lu.tudor.santec.gecamed.formeditor.gui.component.FormToggleButton;
import lu.tudor.santec.gecamed.formeditor.gui.controller.FormPopupController;
import lu.tudor.santec.gecamed.formeditor.gui.controller.FormSplitPaneController;
import lu.tudor.santec.gecamed.formeditor.gui.controller.action.FormEntryDeleteAction;
import lu.tudor.santec.gecamed.formeditor.gui.controller.action.FormEntryOpenAction;
import lu.tudor.santec.gecamed.formeditor.gui.model.FormModel;
import lu.tudor.santec.gecamed.formeditor.gui.view.dialog.NewFormDialog;
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.PatientButtonPanel;
import lu.tudor.santec.gecamed.patient.gui.PatientManagerModule;
import lu.tudor.santec.gecamed.patient.gui.PatientPanel;
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 com.jgoodies.forms.layout.CellConstraints;
import com.jgoodies.forms.layout.FormLayout;

public class FormTab extends PatientViewTab implements IEntryTypeHandler, IEntryPrintRenderer {
	
	private static final long serialVersionUID = 1L;
	
	/** the logger Object for this class */
	private static Logger logger = Logger.getLogger(FormTab.class.getName());
	
	public static final String NAME = "form";
	public static final String TEMPLATE_MARK = "template_#";

	public static final String TAB_NAME = "FormViewTab";
	
	
	private static DateFormat formater = DateFormat.getDateTimeInstance(
			DateFormat.SHORT, DateFormat.SHORT);
	
	
	private PatientPanel 				patientPanel;
	
	private Patient 					currentPatient;

	private FormIncidentEntryRenderer 	incidentRenderer;
	
	private Collection<JComponent> 		actionComponents = new ArrayList<JComponent>();
	
	private Map<String, FormModel> 		openedForms;
	
	private JTabbedPane 				formTabs;
	
	private FormSplitPaneController 	splitManager;
	
//	private Collection<FormTemplate> 	templates;
	
	private FormHistoryView 			historyView;
	
	private boolean 					wasShownBefore;
	
	/* ********** Actions for PopupMenu ********** */
	private FormEntryDeleteAction 		deleteAction;
	private FormEntryOpenAction 		openAction;
	/* **************************************** */
	
	
	
	public FormTab (PatientPanel patientPanel) {
		/* ============================================= */
		if (patientPanel == null) {
			return;
		}
		
		super.button = new FormToggleButton();
		super.button.setToolTipText("");
		
		this.patientPanel 	= patientPanel;
		currentPatient 		= this.patientPanel.getPatient();

		
		// =============================
		// =====  BUILD THE PANEL  =====
		// =============================
		
		// Setting the Icon of the PatientViewTab
		this.setOpaque(false);
		this.setIcon(IconFetcher.getMediumIcon(GECAMedModule.class, GECAMedIconNames.TEMPLATE));
		this.setTitle(Translatrix.getTranslationString("formeditor.form.form_title"));
		this.setLayout(new BorderLayout());

		
		this.openedForms = new HashMap<String, FormModel>();
		
		// create and initialize the panels
		initComponents();
		
		// ====================================
		// =====  INIT AND LOAD THE DATA  =====
		// ====================================
		
		incidentRenderer = new FormIncidentEntryRenderer();

 		// add history listener
 		EntryTypeRegister.registerHandler(NAME, this);

 		// =====================================
		//   add a button to create a new form  
		// =====================================
			
		JButton newFormButton = new FormEditorButton(Translatrix.getTranslationString("formeditor.new_form"),
				IconFetcher.getMediumIcon(GECAMedIconNames.class, GECAMedIconNames.TEMPLATE_ADD));
		newFormButton.setToolTipText(Translatrix.getTranslationString("formeditor.new_form_tip"));
		newFormButton.setHorizontalAlignment(SwingConstants.LEFT);
		newFormButton.setEnabled(true);
		newFormButton.setIconTextGap(1);
		newFormButton.setFont(GECAMedFonts.BUTTON_FONT);
		newFormButton.setMargin(new java.awt.Insets(0, 0, 0, 0));
		newFormButton.addActionListener(new ActionListener() 
		{
			public void actionPerformed(ActionEvent e) {
				createForm();
			}
		});
		
		this.actionComponents.add(newFormButton);
	}
	
	
	/**
	 * initializes the panels
	 */
	private void initComponents() 
	{
		/* ********** initialize Actions ********** */
		this.deleteAction = new FormEntryDeleteAction();
		this.openAction = new FormEntryOpenAction();
		/* **************************************** */
		
		/* ********** initialize the FormTab ********** */
		this.setBackground(Color.WHITE);
		this.setOpaque(true);
	
		// create the ScrollPane around the TaskPanes
		JPanel p = new JPanel(new FormLayout("f:p:g", "f:p:g"));
		historyView = new FormHistoryView(patientPanel, this);
		p.add(historyView, new CellConstraints(1, 1));
		p.setOpaque(false);
		p.setBackground(GECAMedColors.c_GECAMedBackground);
		
		// initialize tabs containing the forms
		formTabs = new JTabbedPane();
		formTabs.setBackground(Color.WHITE);
		
		PatientButtonPanel bPanel = new PatientButtonPanel(Translatrix
				.getTranslationString("formeditor.form.form_title"), 
				GECAMedColors.c_GECAMedDarkerBackground, p);
		bPanel.setOpaque(false);
		bPanel.setBorder(BorderFactory.createRaisedBevelBorder());
		JScrollPane sp = new JScrollPane(bPanel);
		sp.getVerticalScrollBar().setUnitIncrement(16);
		
		// create and define the SplitPane
		splitManager = new FormSplitPaneController(formTabs);
		splitManager.setBottomComponent(sp);
		splitManager.setTopComponent(formTabs);
		this.add(splitManager.getSplitPane(), BorderLayout.CENTER);
		/* **************************************** */
	}
	
	
	@Override
	public void afterShowup()
	{
		super.afterShowup();
		if (!wasShownBefore)
		{
			splitManager.showUp();
			wasShownBefore = true;
		}
	}
	
	
	/**
	 * 
	 */
	public void createForm () 
	{
		NewFormDialog newFormDialog = new NewFormDialog(this.patientPanel);
		FormTemplate template = newFormDialog.show();
		
		if (template != null) 
		{
			FormModel model = FormModel.createNewForm(new FormModel(FormModel.TYPE_FORM), template, GECAMedModule.getCurrentPatient());
			
			FormManager manager = (FormManager) ManagerFactory.getRemote(FormManagerImpl.class);
			
			model.setForm(manager.saveForm(model.getForm()));
			
			this.openForm(model);
			
			// is saved again to write the correct description 
			// into the entry in the history
//			model.save();
			saveData(model);
			
//			PatientManagerModule.getInstance().getPatientPanel()
			this.patientPanel.showPanel(this.getName());
			
			this.patientPanel.reloadHistory();
		}
	}
	
	
	/**
	 * Opens a tab for the FormModel
	 * 
	 * @param model 
	 *  contains the form and the belonging template
	 */
	public void openForm(FormModel model) 
	{
		String key = getKeyForForm(model.getForm());
		
		if (!openedForms.containsKey(key)) 
		{
			// create the FormModelView by loading a FormModel
			JLabel tabLabel = new JLabel(getTabName(model));
			tabLabel.setOpaque(false);
//			model.setTabLabel(tabLabel);
			model.setFormTab(this, tabLabel);
			model.load(false);
			
			// add a tab
			formTabs.addTab("", model.getView());
			formTabs.setTabComponentAt(formTabs.getTabCount() - 1, tabLabel);

			// create the panel for the tab
			JPanel tabPanel = new JPanel(new BorderLayout());
			tabPanel.setOpaque(false);
			
			
			// create the popup-menu for the close and delete button			
			tabLabel.addMouseListener(new FormPopupController(this, model));
			
			
			// add to the available forms
			key = getKeyForForm(model.getForm());
			
			openedForms.put(key, model);
			
			// call initMetode
			model.executeInitMethod();		
		} 
		else 
		{
			model = openedForms.get(key);
		}
		
		// select the clicked form
		formTabs.setSelectedComponent(model.getView());
	}
	

	/**
	 * Closes the tab of the model. If the model was modified, the user is asked
	 * if the changes shell be saved before closing
	 *  
	 * @param model
	 * represents the tab, that shell be closed
	 */
	public void closeForm (FormModel model) 
	{
		closeForm(model, true);
	}
	
	
	/**
	 * Closes the tab of the model. 
	 *  
	 * @param model 
	 * represents the tab, that shell be closed
	 * @param askToSavingChanges
	 * If <code>true</code> and the model was modified, the user is asked
	 * if the changes shell be saved before closing
	 */
	public void closeForm (FormModel model, boolean askToSaveChanges) 
	{
		int buttonMode = GECAMedBaseDialog.YES_OPTION;
		
		if (askToSaveChanges && model.isModified()) 
		{
			// model was modified, ask if the user really wants to save changes before closing	
			buttonMode = GECAMedBaseDialogImpl.showMessageDialog(this, 
					Translatrix.getTranslationString("formeditor.form.save_before_closing_title"), 
					Translatrix.getTranslationString("formeditor.form.save_before_closing")
							.replace("FORM_NAME", model.getName()), 
							GECAMedBaseDialogImpl.YES_NO_CANCEL_BUTTON_MODE);
			
			if (buttonMode == GECAMedBaseDialog.YES_OPTION) {
				// "yes" was clicked, save the changes
				this.saveData(model);
			}
		}
		
		if (buttonMode != GECAMedBaseDialog.CANCEL_OPTION) 
		{
			// if the cancel-button was NOT pressed, close the tab
			model.close();
			
			// remove from map, containing all tabs
			openedForms.remove(getKeyForForm(model.getForm()));
			
			// remove the tab from the JTabbedPane
			formTabs.removeTabAt(formTabs.getSelectedIndex());
		}
	}
	
	public void closeFormWithoutSaving (String key) 
	{
		FormModel 	model 	= openedForms.remove(key);
		JScrollPane view 	= model.getView();
		
		while (formTabs.getComponentCount() > 0) {
			if (formTabs.getComponentAt(0).equals(view)) 
			{
				model.close();
				formTabs.removeTabAt(0);
				return;
			}
		}
	}
	
	public void closeAllForms () {
		/* ======================================== */
		Collection<FormModel> formsToClose = new LinkedList<FormModel>();
		
		// ask, what should happen with the unsaved FormModels
		Integer buttonMode = null;
		
		
		for (FormModel model : openedForms.values()) 
		{
			if (model.isModified() && buttonMode == null) {
				// ask if the forms shall be saved or not or if the action shall be canceled
				buttonMode = GECAMedBaseDialogImpl.showMessageDialog(this, 
						Translatrix.getTranslationString("formeditor.form.save_before_closing_title"), 
						Translatrix.getTranslationString("formeditor.form.save_before_closing_all")
								.replace("FORM_NAME", model.getName()), 
								GECAMedBaseDialogImpl.YES_NO_CANCEL_BUTTON_MODE);
				
				if (buttonMode == GECAMedBaseDialog.CANCEL_OPTION) 
					return;
			}
			
			formsToClose.add(model);
			
			if (model.isModified() && buttonMode == GECAMedBaseDialog.YES_OPTION) 
			{
				// save this model, if it's modified and unsaved changes shall be saved
				saveData(model);
			}
		}
		
		/* close all forms ...
		 * The forms need to be closed here, because otherwise a ConcurrentModificationException 
		 * is thrown as the openedForms Map is changed while closing a form.
		 */
		for (FormModel model : formsToClose) 
		{
			closeForm(model, false);
		}
	}
	
	public void switchTabKey (String oldKey, String newKey) 
	{
		openedForms.put(newKey, openedForms.remove(oldKey));
	}
	
	/**
	 * will be called, if the save-button is pressed
	 */
	@Override
	public void saveData () 
	{
		// calls the save method for every opened form
		for (FormModel model : openedForms.values()) 
		{
			saveData(model);
//			model.executeInitMethod();
		}
	}
	
	
	/**
	 * Saves the changes for this model ( = one form) in the DB, if there are any changes.
	 * 
	 * @param manager
	 * is used to store the form in the DB. If NULL a new one will be created.
	 * 
	 * @param model 
	 * represents the form, that shell be saved.
	 */
	public void saveData (FormModel model) {
		/* ================================================== */
		
		// check, if the form was already stored in the DB		
		Form form = model.getForm();
		
		if (!form.isPersistent()) 
			model.save();
		
		// convert the values collection to a map
		HashMap<String, FormValue> values = new HashMap<String, FormValue>();
		
		Collection<FormValue> valueCollection = form.getValues();
		if (valueCollection != null)
			for (FormValue value : valueCollection) 
				values.put(value.getKey(), value);
		else
			form.setValues(new HashSet<FormValue>());
		
		// reset hasChanges
		boolean hasChanges = false;
		
		// load the values of the components into the FormValues
		Map<String, EditableComponent> 	editableComponents 	= model.getEditableComponents();
		Map<String, JComponent> 		components 			= model.getComponents();
		List<EditableSubForm>			subForms			= new LinkedList<EditableSubForm>();
		for (String key : editableComponents.keySet()) 
		{
			EditableComponent ec = editableComponents.get(key);
			if (!ec.isStoredInDB())
				continue;
			
			ec.setComponent(components.get(key));
			
			/* **********  has the text changed  ********** */
			String text = ec.getText();
			
			if (values.containsKey(key)) 
			{
				// this is an already existing value)
				FormValue value = values.get(key);
				
				if (text == null
						|| value.getValue() == null
						|| !text.equals(value.getValue())) 
				{
					// change the existing FormValue
					value.setValue(text);
					
					// changes found
					hasChanges = true;
				}
			} 
			else //if (!text.equals(ec.getStartText())) 
			{
				// create a new FormValue and assign it to the form
				FormValue value = new FormValue();
				value.setFormId(form.getId());
				value.setKey(key);
				value.setValue(text);
				form.getValues().add(value);
				
				// a new FormValue was created -> changes found
				hasChanges = true;
			}
			
			if (ec instanceof EditableSubForm)
			{
				// TODO: save the sub form
				subForms.add((EditableSubForm) ec);
			}	
			/* **************************************** */
			
			/* **********  has the structure changed  ********** */
			if (!ec.getStructure().equals(ec.getStartStructure())) 
			{
				model.saveStructure(ec.getStructure(), ec.getKey());
			}
			/* **************************************** */
		}
		
		if (model.hasDateCreatedChanged()) {
			hasChanges = true;
		}
		
		// save the form
		if (hasChanges) 
		{
			// the form only needs to be saved, if any changes were made
			model.save();
		} 
		else if (model.isModified()) 
		{
			/* The model is set modified although there are probably no changes.
			 * In that case the model can be set unmodified without saving.
			 */
			model.setModified(false);
		}
		
		for (EditableSubForm editableSubForm : subForms)
		{
			FormModel subFormModel = editableSubForm.getFormModel();
			if (subFormModel.getForm().getSubForm() == null)
				subFormModel.getForm().setSubForm(model.getForm().getId());
			saveData(subFormModel);
		}
		/* ================================================== */
	}
	
	/**
	 * Deletes a form, opened in the TabbedPane
	 *  
	 * @param formModel
	 * 		represents the form
	 */
	public void delete (FormModel formModel) {
		/* ======================================== */
		int buttonMode = GECAMedBaseDialogImpl.showMessageDialog(this, 
				Translatrix.getTranslationString("formeditor.form.delete_form_title"),
				Translatrix.getTranslationString("formeditor.form.delete_form_msg"), 
				GECAMedBaseDialogImpl.OK_CANCEL_BUTTON_MODE);
		
		if (buttonMode == GECAMedBaseDialog.OK_OPTION) {
			/* ---------------------------------------- */
			// OK-Button was pressed
			
			Form form = formModel.getForm();
			
			if (openedForms.containsKey(getKeyForForm(formModel.getForm()))) {
				/* ---------------------------------------- */
//				PatientManagerModule.getInstance().getPatientPanel().showPanel(NAME);
				
				// the form is opened -> close the from before deleting
				closeForm(formModel, false);
				formModel = null;
				/* ---------------------------------------- */
			}
			
			// delete the from ...
			
			// get a FormManager from RMI
			FormManager manager = (FormManager) ManagerFactory.getRemote(FormManagerImpl.class);
			
			manager.deleteForm(form);
			
			// reload the history ...
			final Point viewPosition = this.historyView.getHistoryTablePanel().getScrollPane().getViewport().getViewPosition();
			
			this.patientPanel
//			PatientManagerModule.getInstance().getPatientPanel()
					.reloadHistory();
			
			SwingUtilities.invokeLater(new Runnable() {
				// sets the scroll bar of the history to the old position
				public void run() {
					historyView.getHistoryTablePanel().getScrollPane().getViewport().setViewPosition(viewPosition);
				}
			});
			/* ---------------------------------------- */
		} 
		// else the cancel button was pressed -> do nothing 
		/* ======================================== */
	}
	
	/**
	 * Deletes a form, that needn't be opened in the TabbedPane. 
	 * This method is used to delete forms with a right click on the history table. 
	 * 
	 * @param entry 
	 * 		is used to get the form
	 */
	public void delete (IncidentEntry entry) {
		/* ======================================== */
		FormManager manager = (FormManager)ManagerFactory.getRemote(FormManagerImpl.class);
		Form form = manager.getFormByIncidentEntry(entry.getId());
		
		FormModel formModel = new FormModel (FormModel.TYPE_FORM);
		formModel.setForm(form);
		
		delete(formModel);
		/* ======================================== */
	}
	

	public GECAMedEntityBean getPatient() {
		/* ======================================== */
		return patientPanel.getPatient();
		/* ======================================== */
	}
	
	/**
	 * automatically called if the patient is changed   
	 */
	public void setPatient (Patient patient) 
	{
		// reset the TabbedPane and the stored tabs
		if (currentPatient != null
				&& patient != null
				&& currentPatient.getId() != null
				&& !currentPatient.getId().equals(patient.getId())) 
		{
			openedForms.clear();
			formTabs.removeAll();
//			templates = null;
			historyView.initTypeBox();
		}
		else if (currentPatient == null
				|| !currentPatient.isPersistent())
			historyView.initTypeBox();
		
		currentPatient = patient;		
	}
	
	public static Collection<FormTemplate> getTemplates () 
	{
		FormManager manager = (FormManager) ManagerFactory.getRemote(FormManagerImpl.class);
		
		return manager.getAllTemplates();
	}
	
	@Override
	public String getName() 
	{
		return NAME;
	}
	
	@Override
	public Collection<JComponent> getActionComponents () 
	{
		return actionComponents;
	}
	
	public PatientPanel getPatientPanel () 
	{
		return patientPanel;
	}
	
	/***********************************
	 *****  STATIC FORMAT-METHODS  *****
	 **********************************/
	
	/**
	 * forms the Timestamp to 
	 */
	public String timestampToDateString (Date date) 
	{
		return formater.format(date);
	}
	
	public static String getKeyForForm (Form form) 
	{
//		return form.getDateCreated() + "_" + form.getTemplateId() + "_" + form.getId();
		return String.valueOf(form.getId());
	}
	
	public String getTabName (FormModel model) 
	{
		return "<html>" + model.getTemplate().getName() + 
				" (" + model.getVersion() + ")" +
				"<br>" + timestampToDateString(model.getForm().getDateCreated()) + 
				"</html>";
	}
	
	
	public TableCellRenderer getRenderer(String entryType) 
	{
	    return incidentRenderer;
	}

	
	public IEntryPrintRenderer getPrintRenderer(String entryType) 
	{
		return this;
	}
	
	
	public boolean openEntry(IncidentEntry entry) 
	{
		if (!FormEditorModule.isJavaVersionOK()) {
			return true;
		}
		
		Cursor defaultCursor = this.getCursor();
		
		try {
			// change the Cursor while opening a form
			this.setCursor(new Cursor(Cursor.WAIT_CURSOR));
			PatientManagerModule.getInstance().getPatientPanel().showPanel(NAME);
			
			FormManager manager = (FormManager) ManagerFactory.getRemote(FormManagerImpl.class);
			Form form = manager.getFormByIncidentEntry(entry.getId());
			
			if (form == null) {
				/* ---------------------------------------- */
				int button = GECAMedBaseDialogImpl.showMessageDialog(this, 
						Translatrix.getTranslationString("formeditor.form.empty_reference_title"), 
						Translatrix.getTranslationString("formeditor.form.empty_reference"),
						GECAMedBaseDialogImpl.YES_NO_BUTTON_MODE);
				
				if (button == GECAMedBaseDialog.YES_OPTION) {
					
					IncidentManager incManager = (IncidentManager)ManagerFactory.getRemote(IncidentManagerBean.class);
					incManager.removeIncidentEntry(entry);
					
					PatientManagerModule.getInstance().getPatientPanel().reloadHistory();
				}
				
				return true;
				/* ---------------------------------------- */
			}
			
			
			FormTemplate template = manager.getTemplate(form.getTemplateId());
			
			FormModel model = new FormModel(FormModel.TYPE_FORM);
			model.setTemplate(template);
			model.setForm(form);
			
			this.openForm(model);
			
		    return true;
		    
		} catch (Exception e) {
			logger.log(Level.ERROR, e.getMessage(), e);
			return false;
		} finally {
			// reset the cursor after loading prozess
			this.setCursor(defaultCursor);
		}
		/* ======================================== */
	}
	
//	public Collection<FormModel> getOpenForms () {
//		/* ======================================== */
//		return openedForms.values();
//		/* ======================================== */
//	}

	public Collection<Action> getActions(IncidentEntry entry) {
		/* ======================================== */
		deleteAction.setEntry(entry);
		openAction.setEntry(entry);
		
		// do not enable this method, if the form editor is not ready
		openAction.setEnabled(FormEditorModule.isJavaVersionOK());
		
		Collection<Action> actions = new ArrayList<Action>();
		actions.add(openAction);
		actions.add(deleteAction);
		
		return actions;
		/* ======================================== */
	}
	
	
	public JPopupMenu getPopup(IncidentEntry entry)
	{
		return null;
	}
	

	public HashMap<Integer, Object> getSpecialEntries(String entryType,
			Integer patientId) {
		/* ======================================== */
//		try {
//			/* ---------------------------------------- */
//			FormManager manager = (FormManager)ManagerFactory.getRemote(FormManagerImpl.class);
//			Collection<Form> forms = manager.getFormsOfPatient(patientId);
//			
//			HashMap<Integer, Object> elements = new HashMap<Integer, Object>();
//			for (Form form : forms) {
//				/* ---------------------------------------- */
//				elements.put(form.getIncidentEntry().getId(), form);
//				/* ---------------------------------------- */
//			}
//			
//			return elements;
//			/* ---------------------------------------- */
//		} catch (Exception e) {
//			logger.log(Level.ERROR, e.getMessage(), e);
//		}
		return null;
		/* ======================================== */
	}
	
	@Override
	public void enableTab() {
		if (FormEditorModule.isJavaVersionOK()) {
			super.enableTab();
		} else {
			super.disableTab();
		}
	}


	public String renderPrintEntry(IncidentEntry entry)
	{
		String text = entry.getTextContent();
		int titleIndex = text.indexOf("</title>");
		if (titleIndex >= 0)
		{
			text = text.substring(titleIndex);
			text = text.replace("<br>", "\n\t");
//			text = text.replace("</title>", "\n\t");
			text = text.replaceAll("<.*?>", "");
		}
		
		return Translatrix.getTranslationString("formeditor.form") + ": " + text + "\n";
	}
}
