/*****************************************************************************
 *                                                                           *
 *  Copyright (c) 2010 by SANTEC/TUDOR www.santec.tudor.lu                   *
 *                                                                           *
 *                                                                           *
 *  This library is free software; you can redistribute it and/or modify it  *
 *  under the terms of the GNU Lesser General Public License as published    *
 *  by the Free Software Foundation; either version 2 of the License, or     *
 *  (at your option) any later version.                                      *
 *                                                                           *
 *  This software 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 along with this library; if not, write to the Free Software      *
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA  *
 *                                                                           *
 *****************************************************************************/
package lu.tudor.santec.gecamed.prescription.gui.util;

import java.text.DateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Locale;

import javax.swing.JDialog;

import lu.tudor.santec.gecamed.core.ejb.session.beans.TemplateManagerBean;
import lu.tudor.santec.gecamed.core.ejb.session.interfaces.TemplateManagerInterface;
import lu.tudor.santec.gecamed.core.gui.GECAMedModule;
import lu.tudor.santec.gecamed.core.gui.MainFrame;
import lu.tudor.santec.gecamed.core.gui.widgets.ErrorDialog;
import lu.tudor.santec.gecamed.core.gui.widgets.PrintPreviewDialog;
import lu.tudor.santec.gecamed.core.gui.widgets.print.PrintParameterFetcher;
import lu.tudor.santec.gecamed.core.utils.GECAMedUtils;
import lu.tudor.santec.gecamed.core.utils.JasperTemplateBean;
import lu.tudor.santec.gecamed.core.utils.ManagerFactory;
import lu.tudor.santec.gecamed.core.utils.PrintParameter;
import lu.tudor.santec.gecamed.core.utils.SSNChecker;
import lu.tudor.santec.gecamed.core.utils.printing.ireport.UtilFormatter;
import lu.tudor.santec.gecamed.core.utils.printing.ireport.UtilSettings;
import lu.tudor.santec.gecamed.office.ejb.entity.beans.Office;
import lu.tudor.santec.gecamed.office.ejb.entity.beans.Physician;
import lu.tudor.santec.gecamed.patient.ejb.entity.beans.Patient;
import lu.tudor.santec.gecamed.patient.utils.PatientNameFormatter;
import lu.tudor.santec.gecamed.prescription.ejb.entity.beans.Prescription;
import lu.tudor.santec.gecamed.prescription.ejb.entity.beans.PrescriptionDrug;
import lu.tudor.santec.i18n.Translatrix;
import net.sf.jasperreports.engine.JRDataSource;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;

import org.apache.log4j.Level;
import org.apache.log4j.Logger;

/**
 * Printer class of the prescription modul. All prescriptions are generated by this class. The template is filled with data from the current physian, patient
 * and office. To gain a standard font and layout the templates are generated on server-side because the past has shown that clients can vary in their installed
 * set of fonts.
 * 
 * @author martin.heinemann@tudor.lu
 * 
 * 
 * @version <br>
 *          $Log: PrescriptionPrinter.java,v $
 *          Revision 1.58  2014-02-11 12:31:59  ferring
 *          logging with logger
 *
 *          Revision 1.57  2013-12-27 18:08:02  donak
 *          Cleanup of imports
 *
 *          Revision 1.56  2013-10-10 13:08:56  donak
 *          Upload of prescriptions to eSanté DSP
 *
 *          Revision 1.55  2013-10-10 12:14:06  donak
 *          Integration of cda unique document id is now persistent context menu now adapts to the upload status of a document
 * <br>
 *          Revision 1.54 2013-07-15 06:18:34 ferring <br>
 *          logging changed <br>
 * <br>
 *          Revision 1.53 2013-02-08 10:25:14 ferring <br>
 *          prescription prints over several rows <br>
 * <br>
 *          Revision 1.52 2013-01-22 14:21:28 ferring <br>
 *          iReport templates will now be compiled only once until the server is stopped <br>
 * <br>
 *          Revision 1.51 2012-11-07 10:22:14 troth <br>
 *          *** empty log message *** <br>
 * <br>
 *          Revision 1.50 2012-11-07 10:17:02 troth <br>
 *          *** empty log message *** <br>
 * <br>
 *          Revision 1.49 2012-11-07 10:06:02 troth <br>
 *          Change font size for prescription. <br>
 * <br>
 *          Revision 1.48 2012-07-18 07:49:21 ferring <br>
 *          SSN constants and formating removed from class SSNField and added to class Patient to give the server access to it <br>
 * <br>
 *          Revision 1.47 2012-05-07 12:52:02 ferring <br>
 *          SSN entering changed <br>
 * <br>
 *          Revision 1.46 2011-10-05 08:28:58 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.45 2011-02-08 07:11:24 ferring <br>
 *          iReport parameter added for prescription printing <br>
 * <br>
 *          Revision 1.44 2011-01-07 14:02:53 ferring <br>
 *          The search for the printing template will now take the date into consideration <br>
 * <br>
 *          Revision 1.43 2010-11-15 10:24:57 troth <br>
 *          removed some system.out.println <br>
 * <br>
 *          Revision 1.42 2010-09-01 12:02:57 troth <br>
 *          Incomplete - # 301: Prescription date appears in the accident filed in print out <br>
 *          http://santec.tudor.lu/trac/gecamed/ticket/301 <br>
 * <br>
 *          Revision 1.41 2010-08-23 13:29:14 troth <br>
 *          update iReport print formula prescription and certificate. standardize methods to print patient name, physician name and caisse maladie. <br>
 * <br>
 *          Revision 1.40 2010-08-20 12:01:35 troth <br>
 *          Incomplete - # 603: Formatierung der Matricle Nummer <br>
 *          http://santec.tudor.lu/trac/gecamed/ticket/603 <br>
 * <br>
 *          Revision 1.39 2010-07-19 15:15:34 troth <br>
 *          #557: add caisse de maladie to the prescription printout <br>
 *          http://santec.tudor.lu/trac/gecamed/ticket/557 <br>
 * <br>
 *          Revision 1.38 2010-07-08 14:25:17 hermen <br>
 *          added <br>
 *          param.put("patientCaisse", patient.getInsurance().getAcronym()); <br>
 *          // for possible customizations <br>
 *          param.put("patient", patient); <br>
 *          to report <br>
 * <br>
 *          Revision 1.37 2010-07-08 14:23:44 hermen <br>
 *          added <br>
 *          param.put("patientCaisse", patient.getInsurance().getAcronym()); <br>
 *          // for possible customizations <br>
 *          param.put("patient", patient); <br>
 *          to report <br>
 * <br>
 *          Revision 1.36 2010-07-06 13:20:43 troth <br>
 *          Use the new functions from the class TemplateFormatter to print patient name and address. <br>
 * <br>
 *          Revision 1.35 2010-07-01 11:32:11 troth <br>
 *          Incomplete - # 259: Orddononce callibrateur / multipage prescriptions -> #280, #359 <br>
 *          http://santec.tudor.lu/trac/gecamed/ticket/259 <br>
 * <br>
 *          Revision 1.34 2010-04-27 15:12:21 mack <br>
 *          Changes required by changes in template formatting class <br>
 * <br>
 *          Revision 1.33 2010-04-08 14:57:14 hermen <br>
 *          jasper templates are now compiled on demand from the jrxml files <br>
 * <br>
 *          Revision 1.32 2009-06-29 12:43:40 hermen <br>
 *          changed getting Zipcode for Printing <br>
 * <br>
 *          Revision 1.31 2009-03-23 13:16:54 heinemann <br>
 *          fixed Ticket #264 Printing prescription blocks when hitting "Print" button in preview window <br>
 * <br>
 *          printpreview dialog now owns a constructor that recieve a prent different from the mainframe. <br>
 * <br>
 *          Revision 1.30 2008-12-18 10:55:50 heinemann <br>
 *          finished update method for prescription module <br>
 * <br>
 *          Revision 1.29 2008-12-17 15:23:06 heinemann <br>
 *          initial commit after merging of branch new prescription <br>
 * <br>
 *          Revision 1.28.2.1 2008-12-15 14:08:21 heinemann <br>
 *          *** empty log message *** <br>
 * <br>
 *          Revision 1.28 2008-10-27 14:44:04 hermen <br>
 *          now prints uppercase locations in the address <br>
 * <br>
 *          Revision 1.27 2008-10-14 13:30:47 heinemann <br>
 *          *** empty log message *** <br>
 * <br>
 *          Revision 1.26 2008-10-13 09:26:47 heinemann <br>
 *          *** empty log message *** <br>
 * <br>
 *          Revision 1.25 2008-09-25 09:43:06 heinemann <br>
 *          fixed copyrights <br>
 * <br>
 *          Revision 1.24 2008-08-21 15:45:12 heinemann <br>
 *          removed the bogus behaviour when there is no office entry in the database. The fields on the print outs are now left blank. The user gets an
 *          information that the office address is missing. <br>
 * <br>
 *          Revision 1.23 2008-08-19 10:25:08 heinemann <br>
 *          cleanup <br>
 * <br>
 *          Revision 1.22 2008-07-04 14:03:04 mack <br>
 *          Removed RP/ from prescription string. Is added in template <br>
 * <br>
 *          Revision 1.21 2008-06-02 14:49:31 hermen <br>
 *          changed prescription date format <br>
 * <br>
 *          Revision 1.20 2008-05-29 10:08:20 hermen <br>
 *          now uses physician address for printing if set, else office address <br>
 * <br>
 *          Revision 1.19 2008-02-05 15:06:58 hermen <br>
 *          fixed empty address NPE <br>
 * <br>
 *          Revision 1.18 2008-01-15 09:58:54 heinemann <br>
 *          better documentation <br>
 * <br>
 *          Revision 1.17 2007-11-22 15:08:05 heinemann <br>
 *          RUE to rue <br>
 * <br>
 *          Revision 1.16 2007-11-20 08:58:55 hermen <br>
 *          moved Managerfactory to core.utils and refactured code to use ManagerFactory instead of context.lookup <br>
 * <br>
 *          Revision 1.15 2007-09-11 15:01:58 heinemann <br>
 *          added iso address layout for abroad addresses <br>
 * <br>
 *          Revision 1.14 2007/07/31 09:16:06 hermen <br>
 *          print demo prescriptions in demo version <br>
 * <br>
 *          Revision 1.13 2007/07/16 09:13:00 heinemann <br>
 *          *** empty log message *** <br>
 * <br>
 *          Revision 1.12 2007/07/06 08:22:00 heinemann <br>
 *          generate prescription on server side now to have consistent print outs <br>
 * <br>
 *          Revision 1.11 2007/07/04 10:40:17 heinemann <br>
 *          *** empty log message *** <br>
 * <br>
 *          Revision 1.10 2007/07/03 12:35:29 heinemann <br>
 *          system.out removed <br>
 * <br>
 *          Revision 1.9 2007/07/03 11:47:05 heinemann <br>
 *          *** empty log message *** <br>
 * <br>
 *          Revision 1.8 2007/04/26 13:40:19 heinemann <br>
 *          added <Family Name> <MaidenName> <FirstName> <br>
 * <br>
 *          Revision 1.7 2007/04/12 07:05:04 heinemann <br>
 *          fixed nullpointer when MAIDEN_Config is not avalable from the settings. <br>
 * <br>
 *          Revision 1.6 2007/03/28 07:14:58 heinemann <br>
 *          incomplete: configure maiden name behaviour in the adminstrative settings. <br>
 *          TODO: use the setting in the BillingPrinterBean <br>
 * <br>
 *          Revision 1.5 2007/03/27 11:57:24 heinemann <br>
 *          switched marriage and maidenname for the address field. <br>
 *          If the patient has a marriage name, this will be used as lastname for the postal address. <br>
 * <br>
 *          Revision 1.4 2007/03/13 10:08:41 heinemann <br>
 *          new print dialog for prescription printing <br>
 * <br>
 *          Revision 1.3 2007/03/07 11:53:05 heinemann <br>
 *          *** empty log message *** <br>
 * <br>
 *          Revision 1.2 2007/03/02 08:28:38 hermen <br>
 *          initial checkin after the merge of PatientModuleRebuild with the main HEAD <br>
 * <br>
 *          Revision 1.1.2.14 2007/02/22 12:01:37 heinemann <br>
 *          *** empty log message *** <br>
 * <br>
 *          Revision 1.1.2.13 2007/01/22 12:21:16 heinemann <br>
 *          Complete - # 41: Print empty prescription <br>
 *          http://santec.tudor.lu:8888/gecamed/ticket/41 <br>
 *          Added button to the navi bar <br>
 * <br>
 *          Revision 1.1.2.12 2007/01/22 10:24:07 heinemann <br>
 *          Incomplete - # 13: print copies of prescriptions <br>
 *          http://santec.tudor.lu:8888/gecamed/ticket/13 <br>
 * <br>
 *          Revision 1.1.2.11 2007/01/19 12:44:17 heinemann <br>
 *          Complete - # 28: Accident Nr and date must appear on the prescription printout <br>
 *          http://santec.tudor.lu:8888/gecamed/ticket/28 <br>
 * <br>
 *          Revision 1.1.2.10 2007/01/19 10:36:34 heinemann <br>
 *          cleaning <br>
 * <br>
 *          Revision 1.1.2.9 2007/01/08 09:31:24 heinemann <br>
 *          Add GSM support for prescription <br>
 * <br>
 *          Revision 1.1.2.8 2007/01/08 08:35:20 hermen <br>
 *          *** empty log message *** <br>
 * <br>
 *          Revision 1.1.2.7 2007/01/04 13:51:37 heinemann <br>
 *          The great space cleaning lady has done a big bunch of refactoring <br>
 * <br>
 *          Revision 1.1.2.6 2006/12/22 14:28:31 heinemann <br>
 *          better layout for drugs <br>
 * <br>
 *          Revision 1.1.2.5 2006/12/22 13:18:09 heinemann <br>
 *          *** empty log message *** <br>
 * <br>
 *          Revision 1.1.2.4 2006/12/21 14:49:37 hermen <br>
 *          *** empty log message *** <br>
 * <br>
 *          Revision 1.1.2.3 2006/12/21 14:26:43 heinemann <br>
 *          *** empty log message *** <br>
 * <br>
 *          Revision 1.1.2.2 2006/12/20 09:34:29 hermen <br>
 *          added preview and printerdialog settings <br>
 * <br>
 *          Revision 1.1.2.1 2006/12/19 14:52:40 heinemann <br>
 *          printing etc <br>
 */
public class PrescriptionPrinter {

	/** the logger Object for this class */
	private static Logger logger = Logger.getLogger(PrescriptionPrinter.class.getName());

	// private static final String TEMPLATE_NAME_PRESCRIPTION = "prescription";
	private static JasperReport jasperReport;

	private static PrintPreviewDialog printPreviewDialog = new PrintPreviewDialog();

	// private static JasperReport compiledDefaultTemplate;

	// private static UtilFormatter formatter = new UtilFormatter ();

	// private static SSNFormatter ssnFormatter = new SSNFormatter();

	// static {
	// try {
	// formatter.setReferenceAddress(MainFrame.getCurrentOffice().getLatestOfficeAddress());
	// } catch (Exception e) {
	// }
	// }

	/**
	 * Show only the print preview of a prescription
	 * 
	 * @param prescription
	 */
	public static void showPrescription(Prescription prescription) {
		/* ====================================================== */
		try {
			JasperPrint prescPrint = generatePrescriptionReport(prescription, (prescription.getExpiryDate() != null ? true : false), false, GECAMedUtils.isDemo());
			/* ------------------------------------------------------ */
			// viewReport(prescPrint);
			printPreviewDialog.doPrint(prescPrint);
		} catch (JRException e) {
			e.printStackTrace();
		}
		/* ====================================================== */
	}

	/**
	 * @param prescription
	 * @param isCopy
	 *            prints a copy sign
	 * @param printDate
	 *            prints the date of the prescription
	 * @return
	 */
	public static boolean print(Prescription prescription, boolean isCopy, boolean printDate) {
		/* ================================================== */
		return print(prescription, isCopy, printDate, null);
		/* ================================================== */
	}

	/**
	 * Generates a prescription document and sends it to the printer
	 * 
	 * @param prescription
	 *            The prescription of which the document should be created
	 * @param isCopy
	 *            Adds a copy sign to the prescription
	 * @param printDate
	 *            Prints the expiration date on the prescription
	 * @param parent
	 *            The component that is the parent of the optional print preview dialog
	 * @return True if the prescription was sucessfully sent to the printer, false otherwise
	 */
	public static boolean print(Prescription prescription, boolean isCopy, boolean printDate, JDialog parent) {
		/* ================================================== */
		try {
			/* ------------------------------------------------------ */
			JasperPrint prescPrint = generatePrescriptionReport(prescription, printDate, isCopy, GECAMedUtils.isDemo());

			/* ------------------------------------------------------- */
			if (parent == null) {
				return printPreviewDialog.doPrint(prescPrint);
			} else {
				/* ------------------------------------------------------- */
				PrintPreviewDialog pp = new PrintPreviewDialog(parent);
				return pp.doPrint(prescPrint);
				/* ------------------------------------------------------- */
			}
			/* ------------------------------------------------------- */
		} catch (Exception e) {
			logger.error("Error while trying to print prescription", e);
			return false;
		}
		/* ================================================== */
	}

	/**
	 * Generates a prescription document
	 * 
	 * @param prescription
	 *            The prescription of which the document should be created
	 * @param printDate
	 *            Prints the expiration date on the prescription
	 * @param iscopy
	 *            Adds a copy sign to the prescription
	 * @param isDemo
	 *            Adds a demo sign on the prescription
	 * @return The prescription document for further processing
	 * @throws JRException
	 *             If an error has been encountered during the generation of the document
	 */
	private static JasperPrint generatePrescriptionReport(Prescription prescription, boolean printDate, boolean iscopy, boolean isDemo) throws JRException {
		/* ====================================================== */
		// load Jasper Template

		HashMap<String, Object> param = PrintParameterFetcher.createDefaultPrintParameter(prescription);
		UtilFormatter formatter = (UtilFormatter) param.get(PrintParameter.PRINT_PARAMETER_FORMATTER);
		UtilSettings settings = (UtilSettings) param.get(PrintParameter.PRINT_PARAMETER_SETTINGS);

		settings.putSetting(UtilSettings.SETTING_IS_COPY, iscopy ? Boolean.TRUE : Boolean.FALSE);

		ArrayList<Object> prescriptionPrintPages = new ArrayList<Object>();
		JRBeanCollectionDataSource dataSource = null;

		param.put("ucmCode", prescription.getPhysicianUcmCode());
		Physician phy = MainFrame.getPhysicianById(prescription.getPhysicianId());

		param.put("drName", formatter.formatPhysicianName(phy, true));// prescription.getPhysicianFullName());
		param.put("drType", prescription.getPhysicianSpeciality());

		// Physician phy = MainFrame.getPhysicianById(prescription.getPhysicianId());
		Office office = MainFrame.getCurrentOffice();
		Patient patient = GECAMedModule.getCurrentPatient();

		param.put("officeName", office.getName());

		param.put("officeAddress", formatter.formatPhysicianAddress(phy));
		param.put("officeAddressLine", formatter.formatPhysicianName(phy, true) + ", " + formatter.formatPhysicianLine(phy));

		StringBuffer phoneBuff = new StringBuffer();
		// tel
		phoneBuff.append(("".equals(prescription.getPhysicianPhone()) ? "" : "Tel: " + prescription.getPhysicianPhone() + "\n"));
		// fax
		phoneBuff.append(("".equals(prescription.getPhysicianFax()) ? "" : "Fax: " + prescription.getPhysicianFax() + "\n"));

		// gsm
		phoneBuff.append(("".equals(prescription.getPhysicianGsm()) ? "" : "Gsm: " + prescription.getPhysicianGsm() + "\n"));
		param.put("officePhone", phoneBuff.toString());

		// String ssn = ssnFormatter.valueToString(prescription.getPatientSocialSecurityNumber());
//		String ssn = Patient.getPrettyFormattedSSN(prescription.getPatientSocialSecurityNumber());
		String ssn = SSNChecker.getFormattedSSN(prescription.getPatientSocialSecurityNumber(), false);
		param.put("patientMatricule", ssn);

		if (patient.getInsurance() != null)
			param.put("patientCaisse", patient.getInsurance().toString());
		else
			param.put("patientCaisse", "");

		// for possible customizations
		param.put("patient", patient);

		// ===================================================================
		// Construct the patients adress
		// We use the patients marriage-name in contrast to ne maiden name
		// maiden name is for insurances
		// marriage name for postal service
		// if this is selected in the settings
		// ===================================================================

		formatter.setPatientNamePrintMode(PatientNameFormatter.CAPITALIZE_WORDS);
		String patientName = formatter.formatPatientName(patient, true, false);
		param.put("patientName", patientName);
		param.put("patientAddress", patientName + System.getProperty("line.separator") + formatter.formatPatientHomeAddress(patient));

		/* ------------------------------------------------------ */
		// accident
		if (prescription.getAccidentNr() != null)
			param.put("accNumber", prescription.getAccidentNr());

		if (prescription.getAccidentDate() != null)
			param.put("accDate", prescription.getAccidentDate());
		/* ------------------------------------------------------ */

		DateFormat formater = DateFormat.getDateInstance(DateFormat.SHORT, Locale.FRENCH);
		try {
			param.put("prescDate", formater.format(prescription.getPrescriptionDate()));
		} catch (Exception e) {
		}

		// expiry date
		if (printDate)
			try {
				param.put("prescExpDate", formater.format(prescription.getExpiryDate()));
			} catch (Exception e) {
			}
		// copy
		if (iscopy)
			param.put("isCopy", true);

		if (isDemo)
			param.put("isDemo", true);
		/* ------------------------------------------------------ */

		Translatrix.addBundle("lu.tudor.santec.gecamed.prescription.gui.resources.Translatrix");

		// create the report
		try {
			TemplateManagerInterface tm = (TemplateManagerInterface) ManagerFactory.getRemote(TemplateManagerBean.class);

			jasperReport = tm.findTemplate(JasperTemplateBean.PRESCRIPTION, prescription.getPhysicianId(), prescription.getPrescriptionDate());
			// Template t = null;
			// try
			// {
			// t = tm.getTemplate(TEMPLATE_NAME_PRESCRIPTION, prescription.getPhysicianId(), prescription.getPrescriptionDate());
			// }
			// catch (Exception e)
			// {
			// logger.error("error fetching template from DB");
			// }
			// if (t != null)
			// {
			// logger.info("using template from DB");
			// jasperReport = (JasperReport) JRLoader.loadObject(new ByteArrayInputStream(t.getJasper()));
			// }
			// else
			// {
			// logger.info("using default template");
			//
			// if (compiledDefaultTemplate == null)
			// {
			// JasperDesign design = (JasperDesign) JRXmlLoader.load(PrescriptionModule.class.getResourceAsStream("templates/OrdonnanceMedicale.jrxml"));
			// compiledDefaultTemplate = tm.compileReport(design);
			// }
			// jasperReport = compiledDefaultTemplate;
			// // jasperReport = (JasperReport)JRLoader.loadObject(PrescriptionModule.class.getResourceAsStream("templates/OrdonnanceMedicale.jasper"));
			// }

		} catch (Exception e) {
			ErrorDialog.showErrorDialog(MainFrame.getInstance(), e);
			logger.log(Level.WARN, " ", e);
		}

		if (prescription.getPrescriptionDrugs() != null && prescription.getPrescriptionDrugs().size() > 0) {

			/* ------------------------------------------------------ */
			StringBuffer buff = new StringBuffer();
			for (PrescriptionDrug drug : prescription.getPrescriptionDrugs()) {
				/* ------------------------------------------------------ */
				buff.append(drug.getName() + "\n");
				// pieces
				// buff.append(" " + drug.getQuantity() + " pc.\n");
				// posology
				buff.append((drug.getPosology() != null && !"".equals(drug.getPosology().trim())) ? drug.getPosology() + "\n\n" : "\n");
				/* ------------------------------------------------------ */
			}
			param.put("prescText", buff.toString());
			/* ------------------------------------------------------ */
		} else {
			// optional content

			// check if new template
			// if (jasperReport.getDetail().getElementByKey("prescription_textfield") == null)
			// {
			param.put("prescText",
					(prescription.getTextContent() != null && !prescription.getTextContent().equals("null") ? prescription.getTextContent() : ""));
			// }
			// else
			// {
			// now split the prescription textcontent in multipages for printing
			if (prescription.getTextContent() != null && !prescription.getTextContent().equals("null")) {
				// add all prescription pages
				// dataSource = new JRBeanCollectionDataSource(createPrescriptionPrintPages(prescription, prescriptionPrintPages));
				prescriptionPrintPages.add(new StringBean(prescription.getTextContent()));
				dataSource = new JRBeanCollectionDataSource(prescriptionPrintPages);
			} else {
				// add empty prescription page
				prescriptionPrintPages.add(new StringBean(""));
				dataSource = new JRBeanCollectionDataSource(prescriptionPrintPages);
			}
			// }
		}

		// set the pageCount
		param.put("pageCount", prescriptionPrintPages.size());
		settings.putSetting("pageCount", new Integer(prescriptionPrintPages.size()));

		try {
			return JasperFillManager.fillReport(jasperReport, param, (JRDataSource) dataSource);
		} catch (Exception e) {
			logger.log(Level.WARN, "unable to generate prescription print", e);
			return null;
		}
		/* ------------------------------------------------------- */

		// let the session bean generate the final prescription
		// TemplateManagerInterface tempManager = (TemplateManagerInterface)
		// ManagerFactory.getRemote(TemplateManagerBean.class);
		// try {
		// return tempManager.createJasperPrint(jasperReport, param);
		// } catch (Exception e) {
		//
		// logger.log(Level.WARN, "unable to generate prescription print", e);
		// return null;
		// }

		// JasperPrint print = JasperFillManager.fillReport(jasperReport, param);

		// return print;
	}

	/**
	 * Transforms a prescription to a pdf
	 * 
	 * @param prescription
	 *            The prescription that should be transformed
	 * @param printDate
	 *            Defines if the expriration date of the prescription should be added
	 * @return A byte array containing the pdf version of the prescription
	 * @throws JRException
	 *             If transformation encountered an error. (Please check stack trace for further details)
	 */
	public static byte[] printPrescriptionToPdf(Prescription prescription, boolean printDate) throws JRException {
		// generate the prescription
		JasperPrint jPrint = generatePrescriptionReport(prescription, printDate, false, false);
		// generate and return a pdf version of the prescription
		return JasperExportManager.exportReportToPdf(jPrint);
	}

	/**
	 * 
	 * Prints an empty prescription except the patients adminstrative data
	 * 
	 * @param patient
	 */
	public static void printEmpty(Patient patient) {

		Prescription p = new Prescription();

		PrescriptionUtils.fillStaticData(p, patient);

		print(p, false, false);
	}

	// /**
	// * split the prescription textcontent in multipages for printing
	// *
	// * @param prescription the prescription
	// * @param prescriptionPrintPages the empty array of prescription pages
	// * @return the filled array of prescription pages
	// */
	// private static ArrayList<Object> createPrescriptionPrintPages(Prescription prescription, ArrayList<Object> prescriptionPrintPages)
	// {
	//
	// // get textfield of JR
	// JRElement jrElementPrescriptionTextField = jasperReport.getDetail().getElementByKey("prescription_textfield");
	//
	// // at the current JR version we can not get the property of the font name and size
	// /*
	// String jrePtfFont = jrElementPrescriptionTextField.getPropertiesMap().getProperty("Font name");
	//
	// String jrePtfSize = jrElementPrescriptionTextField.getPropertiesMap().getProperty("Size");
	//
	// String[] myfield = jrElementPrescriptionTextField.getPropertiesMap().getPropertyNames();
	//
	// for (String mystr : myfield) {
	// System.out.println("prop: " + mystr);
	// }
	// */
	//
	// // so we must set the property of the font name and size fix
	// float widthFactor = 0.6E0F;
	// float heightFator = 9.238E0F;
	//
	// // get graphics handle
	// Graphics g = MainFrame.getInstance().getGraphics();
	// // save font
	// Font saveFont = g.getFont();
	// // set font
	// g.setFont(new Font("Arial", Font.PLAIN, 7));
	// // get font metrics
	// FontMetrics fm = g.getFontMetrics();
	//
	// // find out the height and widht of a JRE - textfield
	// int jrePtfHeight = jrElementPrescriptionTextField.getHeight();
	// int jrePtfWidht = jrElementPrescriptionTextField.getWidth();
	//
	// String textRest = "";
	// String textLine = "";
	// String textWord = "";
	// String textWordPack = "";
	// String newTextPack = "";
	// String textPrintPack = "";
	//
	// int lineCount = 1;
	// int lineWidth = 0;
	// int wordWidth = 0;
	//
	// // get prescription text
	// textRest = new String(prescription.getTextContent());
	//
	// // filter long lines
	// while (textRest.length() > 0)
	// {
	//
	// // get the first textline of text
	// if (textRest.contains("\n"))
	// textLine = textRest.substring(0, textRest.indexOf("\n"));
	// else
	// textLine = textRest.substring(0, textRest.length());
	//
	// // if width of line to long split it
	// if ((fm.stringWidth(textLine) + (textLine.length() * widthFactor)) >= jrePtfWidht)
	// { //
	//
	// while (textLine.length() > 0)
	// {
	//
	// // get first word of textline
	// if (textLine.contains(" "))
	// textWord = textLine.substring(0, textLine.indexOf(" ") + 1);
	// else
	// textWord = textLine.substring(0, textLine.length());
	//
	// //String textSize = textWord + " ";
	// // get length of word
	// wordWidth = fm.stringWidth(textWord);
	// // set length of new textline
	// lineWidth = lineWidth + wordWidth;
	//
	// if ((lineWidth + (textWordPack.length() * widthFactor)) > jrePtfWidht)
	// {
	// lineWidth = wordWidth;
	// // save the part of textline
	// newTextPack = newTextPack + textWordPack + "\n";
	// lineCount++;
	// textWordPack = textWord;// + " ";
	// }
	// else
	// {
	// // add word to wordpack
	// if (textWordPack.equals(""))
	// textWordPack = textWord;// + " ";
	// else
	// textWordPack = textWordPack + textWord;// + " ";
	// }
	//
	// // get the rest of textline
	// if (textLine.contains(" "))
	// textLine = textLine.substring(textLine.indexOf(" ") + 1);
	// else
	// textLine = textLine.substring(textLine.length());
	// }
	// // save the rest of textline
	// newTextPack = newTextPack + textWordPack + "\n";
	// textWordPack = "";
	// lineWidth = 0;
	// }
	// else
	// {
	// newTextPack = newTextPack + textLine + "\n";
	// lineCount++;
	// }
	// // get the rest of the textlines
	// if (textRest.contains("\n"))
	// textRest = textRest.substring(textRest.indexOf("\n") + 1);
	// else
	// textRest = textRest.substring(textRest.length());
	//
	// }
	// textLine = "";
	// lineCount = 1;
	//
	// // split prescription text into printpages
	// while (newTextPack.length() > 0)
	// {
	//
	// // get the first textline of text
	// if (newTextPack.contains("\n"))
	// textLine = newTextPack.substring(0, newTextPack.indexOf("\n"));
	// else
	// textLine = newTextPack.substring(0, newTextPack.length());
	//
	// if (jrePtfHeight < heightFator * lineCount)
	// {
	// //add printpack to print text
	// prescriptionPrintPages.add(new StringBean(textPrintPack));
	// lineCount = 1;
	// textPrintPack = textLine + "\n";
	// }
	// else
	// {
	// // line add
	// if (textPrintPack.equals(""))
	// textPrintPack = textLine + "\n";
	// else
	// textPrintPack = textPrintPack + textLine + "\n";
	// lineCount++;
	// }
	//
	// // get the rest of the textlines
	// if (newTextPack.contains("\n"))
	// newTextPack = newTextPack.substring(newTextPack.indexOf("\n") + 1);
	// else
	// newTextPack = newTextPack.substring(newTextPack.length());
	// }
	//
	// // print last printpack
	// prescriptionPrintPages.add(new StringBean(textPrintPack));
	//
	// // set font back
	// g.setFont(saveFont);
	//
	// return prescriptionPrintPages;
	// }

	public static class StringBean {

		public StringBean(String string) {
			this.string = string;
		}

		private String string;

		public void setString(String string) {
			this.string = string;
		}

		public String getString() {
			return string;
		}
	}
}
