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

import java.text.DateFormat;
import java.util.Calendar;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Vector;

import lu.tudor.santec.gecamed.address.ejb.session.beans.AddressManagerBean;
import lu.tudor.santec.gecamed.address.ejb.session.interfaces.AddressManagerInterface;
import lu.tudor.santec.gecamed.addressbook.ejb.entity.beans.Contact;
import lu.tudor.santec.gecamed.billing.ejb.entity.beans.InvoiceStub;
import lu.tudor.santec.gecamed.billing.ejb.session.beans.SearchInvoiceStubBean;
import lu.tudor.santec.gecamed.billing.ejb.session.interfaces.SearchInvoiceStubInterface;
import lu.tudor.santec.gecamed.billing.utils.BillingAdminSettings;
import lu.tudor.santec.gecamed.core.ejb.entity.beans.PhoneType;
import lu.tudor.santec.gecamed.core.ejb.entity.beans.Title;
import lu.tudor.santec.gecamed.core.gui.GECAMedModule;
import lu.tudor.santec.gecamed.core.gui.MainFrame;
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.utils.ManagerFactory;
import lu.tudor.santec.gecamed.core.utils.printing.ireport.UtilFormatter;
import lu.tudor.santec.gecamed.patient.ejb.entity.beans.Allergies;
import lu.tudor.santec.gecamed.patient.ejb.entity.beans.Antecedents;
import lu.tudor.santec.gecamed.patient.ejb.entity.beans.Incident;
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.HistoryManagerBean;
import lu.tudor.santec.gecamed.patient.ejb.session.beans.PatientAdminBean;
import lu.tudor.santec.gecamed.patient.ejb.session.interfaces.HistoryManager;
import lu.tudor.santec.gecamed.patient.ejb.session.interfaces.PatientAdminInterface;
import lu.tudor.santec.i18n.Translatrix;

import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;


/**
 * PART THAT CONFIGURES THE PLACEHOLDERS OF THE PATIENT
 * 
 * @author martin.heinemann@tudor.lu
 * 26.08.2008
 * 14:27:07
 *
 *
 * @version
 * <br>$Log: OldPlaceholdersConfig.java,v $
 * <br>Revision 1.5  2013-12-27 18:09:26  donak
 * <br>Cleanup of imports
 * <br>
 * <br>Revision 1.4  2013-07-15 06:18:37  ferring
 * <br>logging changed
 * <br>
 * <br>Revision 1.3  2013-03-25 14:27:09  ferring
 * <br>apache commens-lang lib updated
 * <br>
 * <br>Revision 1.2  2012-11-29 08:46:09  ferring
 * <br>Unique constraint added for column name
 * <br>
 * <br>Revision 1.1  2012-11-26 07:56:14  ferring
 * <br>New placeholders are introduced to the letter module
 * <br>The replacement algorithm in Word- and WriterCotnroller has been changed
 * <br>Multicontacts are prepared, but not yet implemented
 * <br>
 * <br>Revision 1.29  2012-01-30 15:29:50  ferring
 * <br>leading zeros added and iReports fixed
 * <br>
 * <br>Revision 1.28  2012-01-27 15:18:18  ferring
 * <br>Maidenname corrected
 * <br>
 * <br>Revision 1.27  2011-10-05 08:28:59  ferring
 * <br>iReport printing changed. Beans added, only one formatter used for everything and reports changed, so that they only use the bean (util) Parameter
 * <br>
 * <br>Revision 1.26  2011-05-09 11:24:35  ferring
 * <br>FormEditor bug fixed, where the fields weren't stored, when the form is being created.
 * <br>Bug fixed while opening a new form called the wrong placeholder replacement method.
 * <br>
 * <br>Revision 1.25  2011-05-06 14:13:28  ferring
 * <br>History for all added and general history entries removed
 * <br>
 * <br>Revision 1.24  2011-05-06 12:29:58  ferring
 * <br>history variables added
 * <br>
 * <br>Revision 1.23  2011-03-02 12:49:38  ferring
 * <br>options added
 * <br>
 * <br>Revision 1.22  2010-06-24 11:55:09  hermen
 * <br>version 1.1
 * <br>
 * <br>Revision 1.21  2010-06-16 07:17:45  hermen
 * <br>*** empty log message ***
 * <br>
 * <br>Revision 1.20  2010-06-15 14:02:59  mack
 * <br>Fixed two bugs in getPatientValues method
 * <br>
 * <br>Revision 1.19  2010-06-08 13:32:13  ferring
 * <br>Made it possible to get data from the DB into an form via placeholders (like it is done in the letter templates)
 * <br>
 * <br>Revision 1.18  2010-04-27 15:08:09  mack
 * <br>Changes required by changes in template formatting class
 * <br>
 * <br>Revision 1.17  2010-03-22 10:10:36  hermen
 * <br>added antecedents to placeholders
 * <br>
 * <br>Revision 1.16  2010-03-19 14:40:43  hermen
 * <br>added antecedents to placeholders
 * <br>
 * <br>Revision 1.15  2010-03-19 11:59:27  hermen
 * <br>added antecedents to placeholders
 * <br>
 * <br>Revision 1.14  2009-07-02 13:15:10  hermen
 * <br>fixed allergies in letters
 * <br>
 * <br>Revision 1.13  2009-05-06 15:59:07  heinemann
 * <br>added some new placeholders
 * <br>
 * <br>Revision 1.12  2008-12-18 13:06:33  mack
 * <br>Translation of titles
 * <br>
 * <br>Revision 1.11  2008-12-15 11:03:38  hermen
 * <br>fixed bug in contact address
 * <br>
 * <br>Revision 1.10  2008-12-12 13:42:56  hermen
 * <br>changed formatting of contact address
 * <br>
 * <br>Revision 1.9  2008-12-12 13:15:19  heinemann
 * <br>added patient title placeholder
 * <br>
 * <br>Revision 1.8  2008-09-25 09:43:06  heinemann
 * <br>fixed copyrights
 * <br>
 * <br>Revision 1.7  2008-09-05 14:17:07  heinemann
 * <br>Fixed placeholders spelling.
 * <br>Fixed problem with placeholders that owns some trailing whitespaces. Replacing works now. In Oo. Word not tested!!!
 * <br>
 * <br>Revision 1.6  2008-08-27 15:34:53  heinemann
 * <br>*** empty log message ***
 * <br>
 *   
 */
class OldPlaceholdersConfig {
	
	/** the logger Object for this class */
	private static Logger logger = Logger.getLogger(PlaceholdersConfig.class.getName());
	
	
	public static final String CATEGORY_PATIENT   = "category_patient";
	public static final String CATEGORY_PHYSICIAN = "category_physician";
	public static final String CATEGORY_CONTACT   = "category_contact";
	public static final String CATEGORY_GENERAL   = "category_general";

	
	/* ---------------------------------------- */
	// placeholders for (whole) history
	/* ---------------------------------------- */
	private static final String HISTORY_START_TEXT 		= "HISTORY";
	public static final String HISTORY_3_DAYS			= HISTORY_START_TEXT + "3DAYS";
	public static final String HISTORY_7_DAYS			= HISTORY_START_TEXT + "7DAYS";
	public static final String HISTORY_30_DAYS			= HISTORY_START_TEXT + "30DAYS";
	public static final String HISTORY_THIS_DAY			= HISTORY_START_TEXT + "THISDAY";
	public static final String HISTORY_LAST_DAY			= HISTORY_START_TEXT + "LASTDAY";
	public static final String HISTORY_THIS_WEEK		= HISTORY_START_TEXT + "THISWEEK";
	public static final String HISTORY_LAST_WEEK		= HISTORY_START_TEXT + "LASTWEEK";
	public static final String HISTORY_THIS_MONTH		= HISTORY_START_TEXT + "THISMONTH";
	public static final String HISTORY_LAST_MONTH		= HISTORY_START_TEXT + "LASTMONTH";
	public static final String HISTORY_ALL				= HISTORY_START_TEXT + "ALL";
	
	/* ------------------------------------------------------- */
	// placeholders for patient category
	/* ------------------------------------------------------- */
	public static final String PATIENT_FIRSTNAME 			= "PATIENTFIRSTNAME";
	public static final String PATIENT_SURNAME 				= "PATIENTSURNAME";
	public static final String PATIENT_MAIDENNAME 			= "PATIENTMAIDENNAME";
	public static final String PATIENT_PATIENT 				= "PATIENT";
	public static final String PATIENT_HOMEADDRESS 			= "PATIENTHOMEADDRESS";
	public static final String PATIENT_SOCIALSECURITYNUMBER = "SOCIALSECURITYNUMBER";
	public static final String PATIENT_ACTIVEPROBLEMS 		= "ACTIVEPROBLEMS";
	public static final String PATIENT_ALLERGIES 			= "ALLERGIES";
	public static final String PATIENT_ANTECEDENTS 			= "ANTECEDENTS";
	public static final String PATIENT_CHRONICALTREATMENTS 	= "CHRONICALTREATMENTS";
	public static final String PATIENT_TITLE 				= "TITLE";
	public static final String PATIENT_LAST_INVOICE_NUMBER	= "LASTINVOICENUMBER";
	public static final String PATIENT_LAST_INVOICE_DATE	= "LASTINVOICEDATE";
	public static final String PATIENT_LAST_CONSULTATION	= "LASTCONSULTATION";
	
	private static final String PATIENT_TEXT				= "PATIENT";
	private static final String PATIENT_HISTORY_START_TEXT 	= PATIENT_TEXT + HISTORY_START_TEXT;
	public static final String PATIENT_HISTORY_3_DAYS		= PATIENT_TEXT + HISTORY_3_DAYS;
	public static final String PATIENT_HISTORY_7_DAYS		= PATIENT_TEXT + HISTORY_7_DAYS;
	public static final String PATIENT_HISTORY_30_DAYS		= PATIENT_TEXT + HISTORY_30_DAYS;
	public static final String PATIENT_HISTORY_THIS_DAY		= PATIENT_TEXT + HISTORY_THIS_DAY;
	public static final String PATIENT_HISTORY_LAST_DAY		= PATIENT_TEXT + HISTORY_LAST_DAY;
	public static final String PATIENT_HISTORY_THIS_WEEK	= PATIENT_TEXT + HISTORY_THIS_WEEK;
	public static final String PATIENT_HISTORY_LAST_WEEK	= PATIENT_TEXT + HISTORY_LAST_WEEK;
	public static final String PATIENT_HISTORY_THIS_MONTH	= PATIENT_TEXT + HISTORY_THIS_MONTH;
	public static final String PATIENT_HISTORY_LAST_MONTH	= PATIENT_TEXT + HISTORY_LAST_MONTH;
	public static final String PATIENT_HISTORY_ALL			= PATIENT_TEXT + HISTORY_ALL;
	
	/* ------------------------------------------------------- */
	// placeholder for physician category
	/* ------------------------------------------------------- */
	public static final String PHYSICIAN_PHYICIAN 		= "PHYSICIAN";
	public static final String PHYSICIAN_ADDRESS 		= "PHYSICIANADDRESS";
	public static final String PHYSICIAN_MOBILEPHONE 	= "PHYSICIANMOBILEPHONE";
	public static final String PHYSICIAN_PHONE		 	= "PHYSICIANPHONE";
	public static final String PHYSICIAN_FAX 			= "PHYSICIANFAX";
	public static final String PHYSICIAN_UCM 			= "PHYSICIANUCM";
	
	/* ------------------------------------------------------- */
	// placeholders for contact category
	/* ------------------------------------------------------- */
	public static final String CONTACT_NAME 			= "CONTACTNAME";
	public static final String CONTACT_ADDRESS 			= "CONTACTADDRESS";
	public static final String CONTACT_ADDRESS_LINE 	= "CONTACTADDRESSLINE";
	public static final String CONTACT_EMAIL 			= "CONTACTEMAIL";
	public static final String CONTACT_FAX 				= "CONTACTFAX";
	public static final String CONTACT_LASTNAME 		= "CONTACTLASTNAME";
	public static final String CONTACT_FIRSTNAME 		= "CONTACTFIRSTNAME";
	public static final String CONTACT_MOBILEPHONE 		= "CONTACTMOBILEPHONE";
	public static final String CONTACT_PHONE_PRIVATE 	= "CONTACTPHONEPRIVATE";
	public static final String CONTACT_PHONE_WORK 		= "CONTACTPHONEWORK";
	public static final String CONTACT_TITLE 			= "CONTACTTITLE";
	public static final String CONTACT_UCM 				= "CONTACTUCM";
	
	/* ------------------------------------------------------- */
	// placeholders for general category
	/* ------------------------------------------------------- */
	public static final String GENERAL_DATE 			= "DATE";
	public static final String GENERAL_TIME 			= "TIME";
	
	
	
	
	public static HashMap<String, Vector<String>> placeHolderCategories = new HashMap<String, Vector<String>>();
	
	private static DateFormat dateFormater = DateFormat.getDateInstance(DateFormat.SHORT, Translatrix.getLocale());
	private static DateFormat timeFormater = DateFormat.getTimeInstance(DateFormat.SHORT, Translatrix.getLocale());
	private static DateFormat datetimeFormater = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT, Translatrix.getLocale());
//	private static AddressFormatter addressFormatter = new AddressFormatter ();
	private static UtilFormatter templateFormatter = new UtilFormatter ((AddressManagerInterface) ManagerFactory.getRemote(AddressManagerBean.class));
	
	static {
		/* ------------------------------------------------------- */
		Vector<String> patientProperties = new Vector<String>();
		patientProperties.add(PATIENT_FIRSTNAME);
		patientProperties.add(PATIENT_SURNAME);
		patientProperties.add(PATIENT_MAIDENNAME);
		patientProperties.add(PATIENT_TITLE);
		patientProperties.add(PATIENT_PATIENT);
		patientProperties.add(PATIENT_HOMEADDRESS);
		patientProperties.add(PATIENT_SOCIALSECURITYNUMBER);
		patientProperties.add(PATIENT_ACTIVEPROBLEMS);
		patientProperties.add(PATIENT_ALLERGIES);
		patientProperties.add(PATIENT_CHRONICALTREATMENTS);
		patientProperties.add(PATIENT_ANTECEDENTS);
		patientProperties.add(PATIENT_LAST_CONSULTATION);
		patientProperties.add(PATIENT_HISTORY_3_DAYS);
		patientProperties.add(PATIENT_HISTORY_7_DAYS);
		patientProperties.add(PATIENT_HISTORY_30_DAYS);
		patientProperties.add(PATIENT_HISTORY_THIS_DAY);
		patientProperties.add(PATIENT_HISTORY_LAST_DAY);
		patientProperties.add(PATIENT_HISTORY_THIS_WEEK);
		patientProperties.add(PATIENT_HISTORY_LAST_WEEK);
		patientProperties.add(PATIENT_HISTORY_THIS_MONTH);
		patientProperties.add(PATIENT_HISTORY_LAST_MONTH);
		patientProperties.add(PATIENT_HISTORY_ALL);
		patientProperties.add(PATIENT_LAST_INVOICE_DATE);
		patientProperties.add(PATIENT_LAST_INVOICE_NUMBER);
		/* ------------------------------------------------------- */
		// the physician properties
		/* ------------------------------------------------------- */
		Vector<String> physicianProperties = new Vector<String>();
		physicianProperties.add(PHYSICIAN_PHYICIAN);
		physicianProperties.add(PHYSICIAN_ADDRESS);
		physicianProperties.add(PHYSICIAN_PHONE);
		physicianProperties.add(PHYSICIAN_MOBILEPHONE);
		physicianProperties.add(PHYSICIAN_FAX);
		physicianProperties.add(PHYSICIAN_UCM);
		/* ------------------------------------------------------- */
		// contact properties
		/* ------------------------------------------------------- */
		Vector<String> contactProperties = new Vector<String>();
		contactProperties.add(CONTACT_NAME);
		contactProperties.add(CONTACT_ADDRESS);
		contactProperties.add(CONTACT_ADDRESS_LINE);
		contactProperties.add(CONTACT_EMAIL);
		contactProperties.add(CONTACT_FAX);
		contactProperties.add(CONTACT_LASTNAME);
		contactProperties.add(CONTACT_FIRSTNAME);
		contactProperties.add(CONTACT_MOBILEPHONE);
		contactProperties.add(CONTACT_PHONE_PRIVATE);
		contactProperties.add(CONTACT_PHONE_WORK);
		contactProperties.add(CONTACT_TITLE);
		contactProperties.add(CONTACT_UCM);
		/* ------------------------------------------------------- */
		// general properties
		/* ------------------------------------------------------- */
		Vector<String> generalProperties = new Vector<String>();
		generalProperties.add(GENERAL_DATE);
		generalProperties.add(GENERAL_TIME);
//		generalProperties.add(HISTORY_3_DAYS);
//		generalProperties.add(HISTORY_7_DAYS);
//		generalProperties.add(HISTORY_30_DAYS);
//		generalProperties.add(HISTORY_THIS_DAY);
//		generalProperties.add(HISTORY_LAST_DAY);
//		generalProperties.add(HISTORY_THIS_WEEK);
//		generalProperties.add(HISTORY_LAST_WEEK);
//		generalProperties.add(HISTORY_THIS_MONTH);
//		generalProperties.add(HISTORY_LAST_MONTH);
		
		
		/* ------------------------------------------------------- */
		// fill the hashmap
		/* ------------------------------------------------------- */
		placeHolderCategories.put(CATEGORY_GENERAL,   generalProperties);
		placeHolderCategories.put(CATEGORY_PATIENT,   patientProperties);
		placeHolderCategories.put(CATEGORY_PHYSICIAN, physicianProperties);
		placeHolderCategories.put(CATEGORY_CONTACT,   contactProperties);
		/* ------------------------------------------------------- */
	}
	
//	public static String[] placeholdersPatient= { "PATIENTFIRSTNAME",
//		"PATIENTSURNAME", "PATIENTMAIDENNAME", "PATIENT",
//		"PATIENTHOMEADDRESS", "SOCIALSECURITYNUMBER", "ACTIVEPROBLEMS",
//		"ALLERGIES", "CHRONICALTREATMENTS"};
//	
//	
//	public static String[] placeholdersDoctor = { "DOCTOR", "DOCTORADDRESS",
//			"DOCTORMOBILEPHONE", "DOCTORFAX", "DOCTORUCM" };
//
//	public static String[] placeholdersContact = { "CONTACTNAME",
//			"CONTACTADDRESS", "CONTACTEMAIL", "CONTACTFAX", "CONTACTLASTNAME",
//			"CONTACTFIRSTNAME", "CONTACTMOBILEPHONE", "CONTACTPHONEPRIVATE",
//			"CONTACTPHONEWORK", "CONTACTTITLE", "CONTACTUCM" };
	
	
	/**
	 * @param category
	 * @return
	 */
	public static HashMap<String, String> generateCategory(String category) {
		/* ================================================== */
		return generateCategory(category, null);
		/* ================================================== */
	}
	
	
	/**
	 * @param category the contact object that should be used to fill the hashmap
	 * @param contact 
	 * @return
	 */
	public static HashMap<String, String> generateCategory(String category, Contact contact) {
		/* ================================================== */
		HashMap<String, String> placeholderMap = new HashMap<String, String>();
		
		/* ------------------------------------------------------- */
		// start filling data
		/* ------------------------------------------------------- */
		Vector<String> placeholderVector = placeHolderCategories.get(category);
		/* ------------------------------------------------------- */
		for (String patientProp : placeholderVector) {
			if (CATEGORY_PATIENT.equals(category)) {
				/* ------------------------------------------------------- */
				placeholderMap.put(patientProp, getPatientValues(patientProp));
				/* ------------------------------------------------------- */
			}
			else if (CATEGORY_PHYSICIAN.equals(category)) {
				/* ------------------------------------------------------- */
				placeholderMap.put(patientProp, getPhysicianValues(patientProp));
				/* ------------------------------------------------------- */
			}
			else if (CATEGORY_CONTACT.equals(category) && contact != null) {
				/* ------------------------------------------------------- */
				placeholderMap.put(patientProp, getContactValues(patientProp, contact));
				/* ------------------------------------------------------- */
			}
			else if (CATEGORY_GENERAL.equals(category)) {
				/* ------------------------------------------------------- */
				placeholderMap.put(patientProp, getGeneralValues(patientProp));
				/* ------------------------------------------------------- */
			}
		}
		return placeholderMap;
		/* ================================================== */
	}
	
	
	public static String getValue (String key, String category)
	{
		return getValue(key, category, null);
	}
	
	
	public static String getValue (String key, String category, Contact contact)
	{
		String text;
		
		if (CATEGORY_CONTACT.equals(category))
			if (contact != null)
				text = getContactValues(key, contact);
			else
				text = "";
		else if (CATEGORY_GENERAL.equals(category))
			text = getGeneralValues(key);
		else if (CATEGORY_PATIENT.equals(category))
			text = getPatientValues(key);
		else if (CATEGORY_PHYSICIAN.equals(category))
			text = getPhysicianValues(key);
		else 
			text = "";
		
		return text;
	}
	
	
	/**
	 * @param key
	 * @return
	 */
	private static String getGeneralValues(String key) {
		/* ================================================== */
		try {
			/* ------------------------------------------------------- */
			if (GENERAL_DATE.equals(key)) {
				/* ------------------------------------------------------- */
				return dateFormater.format(new Date());
				/* ------------------------------------------------------- */
			}
			else if (GENERAL_TIME.equals(key)) {
				/* ------------------------------------------------------- */
				return timeFormater.format(new Date());
				/* ------------------------------------------------------- */
			}
//			else if (key.startsWith(HISTORY_START_TEXT))
//				return getHistoryText(key, null);
			/* ------------------------------------------------------- */
		} catch (Exception e) {
			/* ------------------------------------------------------- */
			logger.log(Level.ERROR, e.getMessage(), e);
			/* ------------------------------------------------------- */
		}
		return "";
		/* ================================================== */
	}
	
	
	/**
	 * @param key
	 * @return
	 */
	private static String getPatientValues(String key) {
		/* ================================================== */
		try {
			/* ------------------------------------------------------- */
			HistoryManager manager = (HistoryManager) ManagerFactory
									.getRemote(HistoryManagerBean.class);
			/* ------------------------------------------------------- */
			if (key == null)
				return "";
			
			if (PATIENT_FIRSTNAME.equals(key)) {
				/* ------------------------------------------------------- */
				return GECAMedModule.getCurrentPatient().getFirstName().toString();
				/* ------------------------------------------------------- */
			}
			/* ------------------------------------------------------- */
			if (PATIENT_SURNAME.equals(key)) {
				/* ------------------------------------------------------- */
				return GECAMedModule.getCurrentPatient().getSurName().toString();
				/* ------------------------------------------------------- */
			}
			/* ------------------------------------------------------- */
			if (PATIENT_MAIDENNAME.equals(key)) {
				/* ------------------------------------------------------- */
				return GECAMedModule.getCurrentPatient().getMaidenName().toString();
				/* ------------------------------------------------------- */
			}
			/* ------------------------------------------------------- */
			if (PATIENT_TITLE.equals(key)) {
				/* ------------------------------------------------------- */
				return Title.translate(GECAMedModule.getCurrentPatient().getTitle().toString());
				/* ------------------------------------------------------- */
			}
			/* ------------------------------------------------------- */
			if (PATIENT_PATIENT.equals(key)) {
				/* ------------------------------------------------------- */
				StringBuffer patient = new StringBuffer();
				
				patient.append(templateFormatter.formatPatientName (GECAMedModule.getCurrentPatient(), true, false));
				patient.append(System.getProperty("line.separator"));
				patient.append(templateFormatter.formatPatientHomeAddress (GECAMedModule.getCurrentPatient()));			
				return patient.toString().replaceAll("\r\n", "\n");
				/* ------------------------------------------------------- */
			}
			/* ------------------------------------------------------- */
			if (PATIENT_HOMEADDRESS.equals(key)) {
				/* ------------------------------------------------------- */
				return templateFormatter.formatPatientHomeAddress(GECAMedModule.getCurrentPatient());
				/* ------------------------------------------------------- */
			}
			/* ------------------------------------------------------- */
			if (PATIENT_SOCIALSECURITYNUMBER.equals(key)) {
				/* ------------------------------------------------------- */
				return GECAMedModule.getCurrentPatient().formatSocialSecurityNumber();
				/* ------------------------------------------------------- */
			}
			/* ------------------------------------------------------- */
			if (PATIENT_ACTIVEPROBLEMS.equals(key)) {
				/* ------------------------------------------------------- */
				return manager.getPatientDatas(GECAMedModule.getCurrentPatient().getId())
								.getActiveProblem().toString();
				/* ------------------------------------------------------- */
			}
			/* ------------------------------------------------------- */
			if (PATIENT_ALLERGIES.equals(key)) {
				/* ------------------------------------------------------- */
				StringBuffer allergies = new StringBuffer("");

				Vector<Allergies> vAllergies = manager.getAllergies(GECAMedModule
														.getCurrentPatient().getId());
				for (Iterator<Allergies> iter = vAllergies.iterator(); iter.hasNext();) {
					Allergies element = iter.next();
					allergies.append(element.getAllergenName());
					if (element.getComment() != null && !("".equals(element.getComment()))) {
					    allergies.append(" (").append(element.getComment()).append(")");
					}
 					if (iter.hasNext())
						allergies.append("\n");
				}
				return allergies.toString();
				/* ------------------------------------------------------- */
			}
			/* ------------------------------------------------------- */
			if (PATIENT_ANTECEDENTS.equals(key)) {
				/* ------------------------------------------------------- */
				StringBuffer antecedents = new StringBuffer("");

				Collection<Antecedents> vAntecedents = manager.getAntecedentsByPatientID(GECAMedModule
					.getCurrentPatient().getId());
				if (vAntecedents != null) {
				    for (Iterator<Antecedents> iter = vAntecedents.iterator(); iter.hasNext();) {
					Antecedents element = (Antecedents) iter.next();
					antecedents.append(element.getShortcut());
					if (element.getDescription() != null && !("".equals(element.getDescription()))) {
//					    antecedents.append("\n");
					    String desc = element.getDescription();
					    desc = desc.replaceAll("(\\r|\\n)", "");
					    desc = desc.replaceAll("\\<br>", System.getProperty("line.separator"));
					    desc = desc.replaceAll("\\<.*?>","");
					    desc = StringEscapeUtils.unescapeHtml4(desc);
					    
					    antecedents.append(desc);
					}
					if (iter.hasNext())
					    antecedents.append("\n");
				    }
				}
				return antecedents.toString();
				/* ------------------------------------------------------- */
			}
			/* ------------------------------------------------------- */
			if (PATIENT_CHRONICALTREATMENTS.equals(key)) {
				/* ------------------------------------------------------- */
				return manager.getPatientDatas(GECAMedModule.getCurrentPatient().getId())
										      .getChronicalTreatments();
				/* ------------------------------------------------------- */
			}
			/* ------------------------------------------------------- */
			if (PATIENT_LAST_CONSULTATION.equals(key)
					|| key.startsWith(PATIENT_HISTORY_START_TEXT)) {
				return getHistoryText(key, manager);
			}
			/* ------------------------------------------------------- */
			if (PATIENT_LAST_INVOICE_NUMBER.equals(key)) {
				/* ------------------------------------------------------- */
				try {
					/* --------------------------------------------- */
					// get the InvoiceStubManager
					/* ------------------------------------------------------- */
					SearchInvoiceStubInterface inManager = (SearchInvoiceStubInterface) ManagerFactory.getRemote(SearchInvoiceStubBean.class);
					InvoiceStub stub = inManager.getLastInvoiceStubForPatient(GECAMedModule.getCurrentPatient().getId());
					
					if (stub != null) {
						/* ------------------------------------------------------- */
						Boolean shortNumber	= Boolean.FALSE;
						Boolean leadingZeros= Boolean.TRUE;
						try {
							/* --------------------------------------------- */
							shortNumber	= (Boolean) MainFrame.getInstance().adminSettingsPanel.getValue(BillingAdminSettings.c_ModuleName, BillingAdminSettings.c_ShortInvoiceNumbersSetting);
							leadingZeros= (Boolean) MainFrame.getInstance().adminSettingsPanel.getValue(BillingAdminSettings.c_ModuleName, BillingAdminSettings.c_UseLeadingZerosSetting);
							/* --------------------------------------------- */
						} catch (Exception e) {
							/* --------------------------------------------- */
							logger.log(Level.ERROR, e.getMessage(), e);
							/* --------------------------------------------- */
						}
						return stub.formatInvoiceNumber(shortNumber.booleanValue(), leadingZeros.booleanValue());
						/* ------------------------------------------------------- */
					}
					/* --------------------------------------------- */
				} catch (Exception e) {
					/* --------------------------------------------- */
					logger.log(Level.ERROR, e.getMessage(), e);
					/* --------------------------------------------- */
				}
				/* ------------------------------------------------------- */
			}
			/* ------------------------------------------------------- */
			if (PATIENT_LAST_INVOICE_DATE.equals(key)) {
				/* ------------------------------------------------------- */
				try {
					/* --------------------------------------------- */
					// get the InvoiceStubManager
					/* ------------------------------------------------------- */
					SearchInvoiceStubInterface inManager = (SearchInvoiceStubInterface) ManagerFactory.getRemote(SearchInvoiceStubBean.class);
					InvoiceStub stub = inManager.getLastInvoiceStubForPatient(GECAMedModule.getCurrentPatient().getId());
					
					if (stub != null) {
						/* ------------------------------------------------------- */
//						Boolean shortNumber = false;
						try {
							/* --------------------------------------------- */
							/*shortNumber = (Boolean)*/ MainFrame.getInstance().adminSettingsPanel.getValue(BillingAdminSettings.c_ModuleName, BillingAdminSettings.c_ShortInvoiceNumbersSetting);
							/* --------------------------------------------- */
						} catch (Exception e) {
							/* --------------------------------------------- */
							logger.log(Level.ERROR, e.getMessage(), e);
							/* --------------------------------------------- */
						}
						return dateFormater.format(stub.getInvoiceDate());
						/* ------------------------------------------------------- */
					}
					/* --------------------------------------------- */
				} catch (Exception e) {
					/* --------------------------------------------- */
					logger.log(Level.ERROR, e.getMessage(), e);
					/* --------------------------------------------- */
				}
				/* ------------------------------------------------------- */
			}
		} catch (Exception e) {
			/* ------------------------------------------------------- */
			logger.log(Level.ERROR, e.getMessage(), e);
			/* ------------------------------------------------------- */
		}
		return "";
		/* ================================================== */
	}
	
	
	private static String checkString(String prefix, String s) {
		/* ================================================== */
		if (s != null)
			return prefix + s;
		return "";
		/* ================================================== */
	}
	
	/**
	 * @param key
	 * @return
	 */
	private static String getPhysicianValues(String key) {
		/* ================================================== */
		try {
			/* ------------------------------------------------------- */
			if (PHYSICIAN_PHYICIAN.equals(key)) {
				/* ------------------------------------------------------- */
				return GECAMedModule.getCurrentPhysician().getTitle()
									+ " "
									+ GECAMedModule.getCurrentPhysician().getFirstName()
									+ " " + GECAMedModule.getCurrentPhysician().getName();
				/* ------------------------------------------------------- */
			}
			/* ------------------------------------------------------- */
			if (PHYSICIAN_ADDRESS.equals(key)) {
				/* ------------------------------------------------------- */
				return templateFormatter.formatPhysicianAddress(GECAMedModule.getCurrentPhysician());				
				/* ------------------------------------------------------- */
			}
			/* ------------------------------------------------------- */
			if (PHYSICIAN_PHONE.equals(key)) {
				/* ------------------------------------------------------- */
				String phone = GECAMedModule.getCurrentPhysician().getPhoneExtension();
				if (phone == null || "".equals(phone.trim())) {
					/* ------------------------------------------------------- */
					// use the office phone
					/* ------------------------------------------------------- */
					return MainFrame.getCurrentOffice().getOfficePhoneByType(PhoneType.HOME).getNumber();
					/* ------------------------------------------------------- */
				}
				return phone;
				/* ------------------------------------------------------- */
			}
			/* ------------------------------------------------------- */
			if (PHYSICIAN_MOBILEPHONE.equals(key)) {
				/* ------------------------------------------------------- */
				return GECAMedModule.getCurrentPhysician().getGsm().toString();
				/* ------------------------------------------------------- */
			}
			/* ------------------------------------------------------- */
			if (PHYSICIAN_FAX.equals(key)) {
				/* ------------------------------------------------------- */
				String fax = GECAMedModule.getCurrentPhysician().getFax();
				if (fax == null || "".equals(fax.trim())) {
					/* ------------------------------------------------------- */
					// use the office fax
					/* ------------------------------------------------------- */
					return MainFrame.getCurrentOffice().getOfficePhoneByType(PhoneType.FAX).getNumber();
					/* ------------------------------------------------------- */
				}
				return fax;
				/* ------------------------------------------------------- */
			}
			/* ------------------------------------------------------- */
			if (PHYSICIAN_UCM.equals(key)) {
				/* ------------------------------------------------------- */
				return GECAMedModule.getCurrentPhysician().getUcmCode().toString();
				/* ------------------------------------------------------- */
			}
			/* ------------------------------------------------------- */
		} catch (Exception e) {
			/* ------------------------------------------------------- */
			/* ------------------------------------------------------- */
		}
		return "";
		/* ================================================== */
	}
	
	
	

	/**
	 * @param key
	 * @return
	 */
	private static String getContactValues(String key, Contact contact) {
		/* ================================================== */
		try {
			/* ------------------------------------------------------- */
			if (CONTACT_NAME.equals(key)) {
				/* ------------------------------------------------------- */
				return contact.toNameString();
				/* ------------------------------------------------------- */
			}
			/* ------------------------------------------------------- */
			if (CONTACT_ADDRESS_LINE.equals(key)) {
				/* ------------------------------------------------------- */
				return templateFormatter.formatContactLine (contact);
				/* ------------------------------------------------------- */
			}
			/* ------------------------------------------------------- */
			if (CONTACT_ADDRESS.equals(key)) {
				/* ------------------------------------------------------- */
				return templateFormatter.formatContactAddress (contact);
				/* ------------------------------------------------------- */
			}
			/* ------------------------------------------------------- */
			if (CONTACT_EMAIL.equals(key)) {
				/* ------------------------------------------------------- */
				return contact.getEmail().toString();
				/* ------------------------------------------------------- */
			}
			/* ------------------------------------------------------- */
			if (CONTACT_FAX.equals(key)) {
				/* ------------------------------------------------------- */
				return contact.getFax().toString();
				/* ------------------------------------------------------- */
			}
			/* ------------------------------------------------------- */
			if (CONTACT_LASTNAME.equals(key)) {
				/* ------------------------------------------------------- */
				return contact.getName().toString();
				/* ------------------------------------------------------- */
			}
			/* ------------------------------------------------------- */
			if (CONTACT_FIRSTNAME.equals(key)) {
				/* ------------------------------------------------------- */
				return contact.getNameFirst().toString();
				/* ------------------------------------------------------- */
			}
			/* ------------------------------------------------------- */
			if (CONTACT_MOBILEPHONE.equals(key)) {
				/* ------------------------------------------------------- */
				return contact.getPhoneMobile().toString();
				/* ------------------------------------------------------- */
			}
			/* ------------------------------------------------------- */
			if (CONTACT_PHONE_PRIVATE.equals(key)) {
				/* ------------------------------------------------------- */
				return contact.getPhonePrivate().toString();
				/* ------------------------------------------------------- */
			}
			/* ------------------------------------------------------- */
			if (CONTACT_PHONE_WORK.equals(key)) {
				/* ------------------------------------------------------- */
				return contact.getPhoneWork().toString();
				/* ------------------------------------------------------- */
			}
			/* ------------------------------------------------------- */
			if (CONTACT_TITLE.equals(key)) {
				/* ------------------------------------------------------- */
				return Title.translate(contact.getTitle().toString());
				/* ------------------------------------------------------- */
			}
			/* ------------------------------------------------------- */
			if (CONTACT_UCM.equals(key)) {
				/* ------------------------------------------------------- */
				return contact.getUcmCode().toString();
				/* ------------------------------------------------------- */
			}
			
			/* ------------------------------------------------------- */
		} catch (Exception e) {
			/* ------------------------------------------------------- */
			/* ------------------------------------------------------- */
		}
		return "";
		/* ================================================== */
	}
	
	
//	/**
//	 * @return
//	 */
//	public static HashMap<String, String> getPlaceholdersMap() {
//		/* ================================================== */
//		HashMap<String, String> placeholderMap = new HashMap<String, String>();
//
//		HistoryManager manager = (HistoryManager) ManagerFactory
//				.getRemote(HistoryManagerBean.class);
//
//		/*
//		 * IncidentManager iManager = (IncidentManager) ManagerFactory
//		 * .getRemote(IncidentManagerBean.class);
//		 */
//		try {
//			placeholderMap.put(placeholdersPatient[0], GECAMedModule
//					.getCurrentPatient().getFirstName());
//		} catch (Exception e) {
//			placeholderMap.put(placeholdersPatient[0], "");
//		}
//		try {
//			placeholderMap.put(placeholdersPatient[1], GECAMedModule
//					.getCurrentPatient().getSurName());
//		} catch (Exception e) {
//			placeholderMap.put(placeholdersPatient[1], "");
//		}
//		try {
//			placeholderMap.put(placeholdersPatient[2], GECAMedModule
//					.getCurrentPatient().getMaidenName());
//		} catch (Exception e) {
//			placeholderMap.put(placeholdersPatient[2], "");
//		}
//
//		placeholderMap.put(placeholdersPatient[3], TemplateFormatter
//				.formatPatientAddress(GECAMedModule.getCurrentPatient(), false)
//				.replaceAll("\r\n", "\n"));
//
//		placeholderMap.put(placeholdersPatient[4], GECAMedModule
//				.getCurrentPatient().getHomeAddress().getFormattedString());
//
//		placeholderMap.put(placeholdersPatient[5], GECAMedModule
//				.getCurrentPatient().formatSocialSecurityNumber());
//
//		try {
//			placeholderMap.put(placeholdersPatientDoctor[6], manager
//					.getPatientDatas(GECAMedModule.getCurrentPatient().getId())
//					.getActiveProblem());
//		} catch (Exception e) {
//			placeholderMap.put(placeholdersPatientDoctor[6], "");
//		}
//
//		try {
//			String allergies = "";
//
//			Vector<Allergies> vAllergies = manager.getAllergies(GECAMedModule
//					.getCurrentPatient().getId());
//
//			for (Iterator iter = vAllergies.iterator(); iter.hasNext();) {
//				Allergies element = (Allergies) iter.next();
//				allergies.concat(element.toString());
//				if (iter.hasNext())
//					allergies.concat(", ");
//			}
//
//			placeholderMap.put(placeholdersPatientDoctor[7], allergies);
//		} catch (Exception e) {
//			placeholderMap.put(placeholdersPatientDoctor[7], "");
//		}
//
//		try {
//			placeholderMap.put(placeholdersPatientDoctor[8], manager
//					.getPatientDatas(GECAMedModule.getCurrentPatient().getId())
//					.getChronicalTreatments());
//		} catch (Exception e) {
//			placeholderMap.put(placeholdersPatientDoctor[8], "");
//		}
//
//		try {
//			placeholderMap.put(placeholdersPatientDoctor[9], GECAMedModule
//					.getCurrentPhysician().getTitle()
//					+ " "
//					+ GECAMedModule.getCurrentPhysician().getFirstName()
//					+ " " + GECAMedModule.getCurrentPhysician().getName());
//		} catch (Exception e) {
//			placeholderMap.put(placeholdersPatientDoctor[9], "");
//		}
//
//		try {
//			if (GECAMedModule.getCurrentPhysician().getPhysicianAddress() != null)
//				placeholderMap.put(placeholdersPatientDoctor[10], GECAMedModule
//						.getCurrentPhysician().getPhysicianAddress()
//						.getFormattedString());
//			else
//				placeholderMap.put(placeholdersPatientDoctor[10], MainFrame
//						.getCurrentOffice().getLatestOfficeAddress()
//						.getFormattedString());
//		} catch (Exception e) {
//			placeholderMap.put(placeholdersPatientDoctor[10], "");
//		}
//
//		try {
//			placeholderMap.put(placeholdersPatientDoctor[11], GECAMedModule
//					.getCurrentPhysician().getGsm());
//		} catch (Exception e) {
//			placeholderMap.put(placeholdersPatientDoctor[11], "");
//		}
//
//		try {
//			placeholderMap.put(placeholdersPatientDoctor[12], GECAMedModule
//					.getCurrentPhysician().getFax());
//		} catch (Exception e) {
//			placeholderMap.put(placeholdersPatientDoctor[12], "");
//		}
//
//		try {
//			placeholderMap.put(placeholdersPatientDoctor[13], GECAMedModule
//					.getCurrentPhysician().getUcmCode());
//		} catch (Exception e) {
//			placeholderMap.put(placeholdersPatientDoctor[13], "");
//		}
//
//		return placeholderMap;
//	}
	
	
	public static HashMap<String, Vector<String>> getPlaceHolders() {
		/* ================================================== */
		return placeHolderCategories;
		/* ================================================== */
	}
	
	/**
	 * Returns a HashMap containing the filled placeholders. If contact is null, the 
	 * placeholders will be empty.
	 * @param contact
	 * @return
	 */
	public static Map<String, String> getPlaceholdersMap(Contact contact) {
		/* ================================================== */
		Map<String, String> map = Collections.synchronizedMap(new HashMap<String, String>());
		
		map.putAll(generateCategory(CATEGORY_GENERAL));
		map.putAll(generateCategory(CATEGORY_PATIENT));
		map.putAll(generateCategory(CATEGORY_PHYSICIAN));
		map.putAll(generateCategory(CATEGORY_CONTACT, contact));
		
		return map;
		/* ================================================== */
	}
	
//	/**
//	 * Takes a String toBeReplaced and replaces all occurrences of the 
//	 * placeholders by the values of the currently chosen patient.
//	 * @param toBeReplaced
//	 * @return
//	 */
//	public static String replaceAllPlaceholders (String toBeReplaced) {
//		/* ======================================== */
//		Map<String, String> placeholder = getPlaceholdersMap(null);
//		String replacedXml = toBeReplaced;
//		for (String key : placeholder.keySet()) {
//			/* ---------------------------------------- */
//			if (!key.equals(PATIENT_PATIENT)
//					&& !key.equals(PHYSICIAN_PHYICIAN)) {
//				/* ---------------------------------------- */
//				/* 
//				 * the strings "PATIENT" and "PHYSICIAN" are ambiguous 
//				 * as they also exist in "PATIENTFIRSTNAME", "PATIENTSURNAME", ...
//				 */
//				if (replacedXml.contains(key))
//				{
//					String replacementText = placeholder.get(key);
//					if (replacementText == null)
//						;
//					replacedXml = replacedXml.replaceAll(key, replacementText);
//				}
//				/* ---------------------------------------- */
//			}
//			/* ---------------------------------------- */
//		}
//		
//		// replace the two ambiguous strings afterwards
//		replacedXml = replacedXml.replaceAll(PATIENT_PATIENT, 
//				placeholder.get(PATIENT_PATIENT));
//		replacedXml = replacedXml.replaceAll(PHYSICIAN_PHYICIAN, 
//				placeholder.get(PHYSICIAN_PHYICIAN));
//		
//		return replacedXml;
//		/* ======================================== */
//	}
	
	
//	public static String[] getPlaceholders() {
//		String[] placeholders = new String[placeholdersPatientDoctor.length
//				+ placeholdersContact.length];
//		for (int i = 0; i < placeholdersPatientDoctor.length; i++) {
//			placeholders[i] = placeholdersPatientDoctor[i];
//		}
//		int k = 0;
//		for (int j = placeholdersPatientDoctor.length; j < placeholders.length; j++) {
//			placeholders[j] = placeholdersContact[k];
//			k++;
//		}
//		return placeholders;
//	}
	
	
	/**
	 * @param entry
	 * @return
	 */
	private static IEntryPrintRenderer getPrintRenderer(IncidentEntry entry) {
		/* ================================================== */
		try {
			/* --------------------------------------------- */
			IEntryTypeHandler handler = EntryTypeRegister.getHandler(entry.getEntryType().getName());
			/* ------------------------------------------------------- */
			return handler.getPrintRenderer(entry.getEntryType().getName());
			/* --------------------------------------------- */
		} catch (Exception e) {
			/* --------------------------------------------- */
			return null;
			/* --------------------------------------------- */
		}
		/* ================================================== */
	}
	

	private static String getHistoryText (String key, HistoryManager manager) throws Exception 
	{
		/* ------------------------------------------------------- */
		StringBuffer buff = new StringBuffer();
		Collection<Incident> latestIncidents;
		
		if (manager == null)
			manager = (HistoryManager) ManagerFactory
					.getRemote(HistoryManagerBean.class);
		
		// define the patient id
		Integer patientId;
		if (key.startsWith(HISTORY_START_TEXT))
			patientId = null;
		else // if (key.startsWith(PATIENT_HISTORY_START_TEXT) || key.equals(PATIENT_LAST_CONSULTATION))
			patientId = GECAMedModule.getCurrentPatient().getId();
		
		if (PATIENT_LAST_CONSULTATION.equals(key))
			latestIncidents = manager.getLatestIncident(patientId, 1);
		else
		{
			// set the start date
			GregorianCalendar startDate = new GregorianCalendar(GECAMedModule.getDefaultLocale());
			startDate.set(Calendar.HOUR_OF_DAY, 0);
			startDate.set(Calendar.MINUTE, 		0);
			startDate.set(Calendar.SECOND, 		0);
			startDate.set(Calendar.MILLISECOND, 0);
			
			// set the end date
			GregorianCalendar endDate 	= new GregorianCalendar(GECAMedModule.getDefaultLocale());
			endDate.set(Calendar.HOUR_OF_DAY, 	23);
			endDate.set(Calendar.MINUTE, 		59);
			endDate.set(Calendar.SECOND, 		59);
			endDate.set(Calendar.MILLISECOND, 	999);
			
			if (key.endsWith(HISTORY_3_DAYS))
			{
				startDate.add(Calendar.DAY_OF_MONTH, -2);
			}
			else if (key.endsWith(HISTORY_7_DAYS))
			{
				startDate.add(Calendar.DAY_OF_MONTH, -6);	
			}
			else if (key.endsWith(HISTORY_30_DAYS))
			{
				startDate.add(Calendar.DAY_OF_MONTH, -29);
			}
			else if (key.endsWith(HISTORY_THIS_DAY))
			{
				// everything is already set
			}
			else if (key.endsWith(HISTORY_THIS_WEEK))
			{
				startDate.set(Calendar.DAY_OF_WEEK, startDate.getFirstDayOfWeek());
			}
			else if (key.endsWith(HISTORY_THIS_MONTH))
			{
				startDate.set(Calendar.DAY_OF_MONTH, 1);
			}
			else if (key.endsWith(HISTORY_LAST_DAY))
			{
				startDate.add(Calendar.DAY_OF_YEAR,	-1);
				endDate.add(Calendar.DAY_OF_YEAR, 	-1);
			}
			else if (key.endsWith(HISTORY_LAST_WEEK))
			{
				// starting at 0 o'clock at the first day of the last week
				startDate.set(Calendar.DAY_OF_WEEK,	startDate.getFirstDayOfWeek());
				startDate.add(Calendar.WEEK_OF_YEAR,-1);

				// ending at 23:59:59 o'clock at the last day of the last week
				endDate.set(Calendar.DAY_OF_WEEK, 	startDate.getFirstDayOfWeek());
				endDate.add(Calendar.DAY_OF_YEAR,	-1);
			}
			else if (key.endsWith(HISTORY_LAST_MONTH))
			{
				// starting at 0 o'clock at the first day of the last month
				startDate.set(Calendar.DAY_OF_MONTH, 1);
				startDate.add(Calendar.MONTH,		-1);
				
				// ending at 23:59:59 o'clock at the last day of the last month
				endDate.set(Calendar.DAY_OF_MONTH, 	 1);
				endDate.add(Calendar.DAY_OF_YEAR,	-1);
			}
			else if (key.endsWith(HISTORY_ALL))
			{
				startDate 	= null;
				endDate 	= null;
			}
			else
			{
				// unsupported place holder
				logger.log(Level.INFO, "unsupported key: " + key);
				return "";
			}
			
			latestIncidents = manager.getPatientIncidents(patientId, startDate, endDate);
		}
		
		String patientTranslation = Translatrix.getTranslationString("main.patient");
		Patient patient;
		PatientAdminInterface patientManager;
		if (patientId == null)
		{
			patientManager 	= (PatientAdminInterface) ManagerFactory.getRemote(PatientAdminBean.class);
			patientId 		= -1;
		}
		else 
		{
			patientManager 	= null;
		}
		
		
		for (Incident latestIncident : latestIncidents)
		{
			// sort the IncidentEntrys
			if (!latestIncident.getPatientId().equals(patientId))
			{
				patientId = latestIncident.getPatientId();
				patient = patientManager.getPatient(patientId);
				buff.append(patientTranslation)
						.append(": ")
						.append(patient.toString())
						.append("\n\n");
			}
			
			List<IncidentEntry> entries = latestIncident.getIncidentEntries();
			Collections.sort(entries);
			
			buff.append(datetimeFormater.format(latestIncident.getIncidentDate()))
					.append("\t")
					.append(templateFormatter.formatPhysicianName(MainFrame.getPhysicianById(
							latestIncident.getPhysicianId()), true))
					.append("\n");
			
			/* ------------------------------------------------------- */
			// assemble the output
			/* ------------------------------------------------------- */
			/* ------------------------------------------------------- */
			// accident data
			/* ------------------------------------------------------- */
			if (latestIncident.getIsAccident()) {
				buff.append(checkString("Acc: ", latestIncident.getAccidentNr()));
				buff.append("\n");
			}
			for (IncidentEntry entry : entries){
				/* ------------------------------------------------------- */
				IEntryPrintRenderer printRenderer = getPrintRenderer(entry);
				if (printRenderer != null) {
					buff.append(printRenderer.renderPrintEntry(entry));
//				} else {
//					buff.append(entry.getEntryType().getName() + ":\t" + entry.getTextContent());
				}
				/* ------------------------------------------------------- */
			}
			buff.append("\n");
		}
		
		return buff.toString();
		/* ------------------------------------------------------- */
	}
}
