/*****************************************************************************
 *                                                                           *
 *  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.ejb.session.beans;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.security.RolesAllowed;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import lu.tudor.santec.gecamed.core.ejb.session.beans.GECAMedSessionBean;
import lu.tudor.santec.gecamed.patient.ejb.entity.beans.IncidentEntry;
import lu.tudor.santec.gecamed.patient.ejb.session.interfaces.IncidentManager;
import lu.tudor.santec.gecamed.prescription.ejb.entity.beans.PosologyTemplate;
import lu.tudor.santec.gecamed.prescription.ejb.entity.beans.Prescription;
import lu.tudor.santec.gecamed.prescription.ejb.entity.beans.PrescriptionRevision;
import lu.tudor.santec.gecamed.prescription.ejb.entity.beans.PrescriptionTemplate;
import lu.tudor.santec.gecamed.prescription.ejb.entity.beans.PrescriptionType;
import lu.tudor.santec.gecamed.prescription.ejb.entity.beans.TemplateDrug;
import lu.tudor.santec.gecamed.prescription.ejb.session.interfaces.PrescriptionManager;
import lu.tudor.santec.gecamed.usermanagement.ejb.session.interfaces.LoginInterface;

import org.apache.log4j.Category;

/**
 * This is the session bean or the prescription module.
 * See interface for method documentation
 * 
 * @author martin.heinemann@tudor.lu
 *
 *
 * @version
 * <br>$Log: PrescriptionManagerBean.java,v $
 * <br>Revision 1.33  2012-01-24 14:38:52  ferring
 * <br>Errors and warnings of Jenkins build corrected
 * <br>
 * <br>Revision 1.32  2010-11-04 13:34:30  troth
 * <br>update of the function that "create Incident Entries for Prescription how have one together" now in the second step the Select select only the needed Prescriptions thats much more faster.
 * <br>
 * <br>Revision 1.31  2010-11-03 17:45:06  troth
 * <br>expansion of the function that "create Incident Entries for Prescription how have one together" now it also
 * <br>1. sync the incidentIds of Prescriptions and there Incident Entry
 * <br>2. deletes Incidents how have no Incident Entries and no back link from a Prescription
 * <br>
 * <br>Revision 1.30  2010-07-22 09:49:39  troth
 * <br>add implementation - # 239: Prescription Templates linked to physician
 * <br>http://santec.tudor.lu/trac/gecamed/ticket/239
 * <br>
 * <br>Revision 1.29  2009-05-06 16:00:05  heinemann
 * <br>added method to generate printable output of the incident entrys
 * <br>
 * <br>Revision 1.28  2008-12-17 15:23:06  heinemann
 * <br>initial commit after merging of branch new prescription
 * <br>
 * <br>Revision 1.27.2.2  2008-12-15 17:16:05  heinemann
 * <br>*** empty log message ***
 * <br>
 * <br>Revision 1.27.2.1  2008-12-15 14:08:21  heinemann
 * <br>*** empty log message ***
 * <br>
 * <br>Revision 1.27  2008-11-12 17:27:13  heinemann
 * <br>*** empty log message ***
 * <br>
 * <br>Revision 1.26  2008-11-12 17:16:33  heinemann
 * <br>*** empty log message ***
 * <br>
 * <br>Revision 1.25  2008-09-25 09:43:10  heinemann
 * <br>fixed copyrights
 * <br>
 * <br>Revision 1.24  2008-07-23 15:17:37  heinemann
 * <br>*** empty log message ***
 * <br>
 * <br>Revision 1.23  2008-07-23 15:13:57  heinemann
 * <br>*** empty log message ***
 * <br>
 * <br>Revision 1.22  2008-07-03 11:59:57  heinemann
 * <br>*** empty log message ***
 * <br>
 * <br>Revision 1.21  2008-03-20 16:08:14  heinemann
 * <br>*** empty log message ***
 * <br>
 * <br>Revision 1.20  2008-03-10 12:37:53  heinemann
 * <br>*** empty log message ***
 * <br>
 * <br>Revision 1.19  2008-03-06 15:34:42  heinemann
 * <br>*** empty log message ***
 * <br>
 * <br>Revision 1.18  2008-01-15 07:43:04  heinemann
 * <br>son doku
 * <br>
 * <br>Revision 1.17  2007/03/12 14:32:10  heinemann
 * <br>Complete - # 46: make printed prescriptions editable
 * <br>http://santec.tudor.lu:8888/gecamed/ticket/46
 * <br>
 * <br>Revision 1.16  2007/03/02 08:28:39  hermen
 * <br>initial checkin after the merge of PatientModuleRebuild with the main HEAD
 * <br>
 * <br>Revision 1.15.2.9  2007/01/15 10:02:32  hermen
 * <br># 9: Improve the posology chooser
 * <br>http://santec.tudor.lu/trac/gecamed/ticket/9
 * <br>
 * <br>added saving / deleting of templates
 * <br>
 * <br>Revision 1.15.2.8  2007/01/15 08:59:14  hermen
 * <br># 9: Improve the posology chooser
 * <br>http://santec.tudor.lu/trac/gecamed/ticket/9
 * <br>
 * <br>added posologytemplates bean
 * <br>
 * <br>Revision 1.15.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.15.2.6  2006/12/28 10:32:01  heinemann
 * <br>bug fixing and template improvements
 * <br>
 * <br>Revision 1.15.2.5  2006/12/22 13:17:40  heinemann
 * <br>*** empty log message ***
 * <br>
 * <br>Revision 1.15.2.4  2006/12/21 14:26:07  heinemann
 * <br>*** empty log message ***
 * <br>
 * <br>Revision 1.15.2.3  2006/12/20 13:46:38  heinemann
 * <br>*** empty log message ***
 * <br>
 * <br>Revision 1.15.2.2  2006/12/15 15:58:25  heinemann
 * <br>presc
 * <br>
 * <br>Revision 1.15.2.1  2006/12/14 09:34:01  heinemann
 * <br>many changes
 * <br>
 */

@Stateless
public class PrescriptionManagerBean extends GECAMedSessionBean implements PrescriptionManager {

	private static final Category logger = Category
	.getInstance(PrescriptionManagerBean.class.getName());

	@PersistenceContext(unitName="gecam")
	EntityManager em;

	@EJB
	LoginInterface login;
	
	@EJB
	IncidentManager incidentManager;


	@SuppressWarnings("unchecked")
	@RolesAllowed("gecam")
	public List<PrescriptionTemplate> getTemplates(String type, Integer physicianId) {
		/* ============================================= */
		try {
			/* ------------------------------------------------------ */
			
			List<PrescriptionTemplate> result =
				em.createNamedQuery(PrescriptionTemplate.GET_USER_TEMPLATES)
					.setParameter("physicianId", physicianId)
					.setParameter("type", type)
					.getResultList();
			return result;
			/* ------------------------------------------------------ */
		} catch (Exception e) {
			/* ------------------------------------------------------ */
			e.printStackTrace();
			return new ArrayList<PrescriptionTemplate>();
			/* ------------------------------------------------------ */
		}
		/* ============================================= */
	}

	@SuppressWarnings("unchecked")
	@RolesAllowed("gecam")
	public List<PrescriptionType> getPrescriptionTypes() {
		/* ============================================= */
		try {
			List<PrescriptionType> result =
				em.createNamedQuery(PrescriptionType.GET_ALL_TYPES)
				.getResultList();
			return result;
		} catch (Exception e) {
			return null;
		}

		/* ============================================= */
	}

	/* (non-Javadoc)
	 * @see lu.tudor.santec.gecamed.prescription.ejb.session.interfaces.PrescriptionManager#savePrescription(java.util.List)
	 */
	@RolesAllowed("gecam")
	public List<Prescription> savePrescription(List<Prescription> modifiedPrescriptions) {
		/* ============================================= */

		final int REV_START = 1;

		Integer userId = login.getCurrentUserID();

		if (modifiedPrescriptions != null) {
			List<Prescription> pNew = new ArrayList<Prescription>();
			/* ------------------------------------------------------ */
			for (Prescription p : modifiedPrescriptions) {
				/* ------------------------------------------------------ */
				/* ------------------------------------------------------- */
				p.setCreatedBy(userId);
				p.setCreationDate(new Date());
				/* ------------------------------------------------------- */
				// check for IncidentEntry
				/* ------------------------------------------------------- */
				if (p.getIncidentEntry() == null) {
					/* ------------------------------------------------------- */
					IncidentEntry entry = incidentManager.getEntryForInsert(p.getIncidentId(), ENTRY_TYPE);
					
					entry = em.merge(entry);
					/* ------------------------------------------------------- */
					p.setIncidentEntry(entry);
					/* ------------------------------------------------------- */
				}
				/* ------------------------------------------------------- */
				// save the prescription
				/* ------------------------------------------------------- */
				p = em.merge(p);
				pNew.add(p);
				// create a new revision object
				PrescriptionRevision pr = new PrescriptionRevision(p);

				/* ------------------------------------------------------- */
				// obtain the revision object
				try {
					PrescriptionRevision prPers = (PrescriptionRevision) em.createNamedQuery(
						PrescriptionRevision.FIND_PRESC_REVISION)
						.setParameter("prescriptionId", p.getId())
						.getSingleResult();
					/* ------------------------------------------------------- */
					pr.setRevisionId(prPers.getRevisionId()+1);
				} catch (Exception e) {
					/* ------------------------------------------------------- */
					pr.setRevisionId(REV_START);
					/* ------------------------------------------------------- */
				}
				/* ------------------------------------------------------- */
				// save the revision
				em.merge(pr);
				/* ------------------------------------------------------ */
			}
			return pNew;
			/* ------------------------------------------------------ */
		}

		return null;
		/* ============================================= */
	}

	@RolesAllowed("gecam")
	public Prescription savePrescription(Prescription prescriptions) {
		/* ============================================= */
		List<Prescription> l = new ArrayList<Prescription>();
		l.add(prescriptions);

		List<Prescription> lNew  = savePrescription(l);
		if (lNew != null)
			return lNew.get(0);
		
		return null;
		/* ============================================= */
	}
	@RolesAllowed("gecam")
	public PrescriptionTemplate saveTemplate(PrescriptionTemplate template) {
		/* ============================================= */
		if (template != null) {
			/* ------------------------------------------------------ */
			// save the template.
			// the relation in the TemplateDrugs is set correctly,
			// when this method is invoked!!
			/* ------------------------------------------------------ */
			// set some user data
			template.setOwnerId(login.getCurrentUserID());
			if (!template.isPersistent())
				template.setCreated(new Date());
			else
				template.setModified(new Date());
			/* ------------------------------------------------------ */
			try {
				/* --------------------------------------------- */
				return em.merge(template);
				/* --------------------------------------------- */
			} catch (Exception e) {
				/* --------------------------------------------- */
				e.printStackTrace();
				/* --------------------------------------------- */
			}
			/* ------------------------------------------------------ */
		}
		return null;
		/* ============================================= */
	}

	@SuppressWarnings("unchecked")
	@RolesAllowed("gecam")
	public List<Prescription> getAntecedentPrescriptions(Integer patientId, Integer typeId) {
		/* ============================================= */
		if (patientId != null && typeId != null) {
			/* ------------------------------------------------------ */
			try {
				/* ------------------------------------------------------ */
				Query q = em.createNamedQuery(Prescription.GET_ANTECEDENT);
				q.setParameter("patientId", patientId);
				q.setParameter("prescriptionTypeId", typeId);
				List<Prescription> result = q.getResultList();

				return result;
				/* ------------------------------------------------------ */
			} catch (Exception e) {
				return null;
			}
			/* ------------------------------------------------------ */
		}
		
		return null;
		/* ============================================= */
	}
	
	/**
	 * Returns all prescriptions that are owned by the incident entry
	 * @param entryId
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public List<Prescription> getPrescriptionByIncidentEntry(Integer entryId) {
		/* ================================================== */
		if (entryId == null)
			return null;
		/* ------------------------------------------------------- */
		Query q = em.createQuery("SELECT OBJECT(o) FROM Prescription o " +
									"WHERE o.incidentEntryId = :entryId " +
									"ORDER BY o.prescriptionDate ASC");
		q.setParameter("entryId", entryId);
		try {
			/* --------------------------------------------- */
			return q.getResultList();
			/* --------------------------------------------- */
		} catch (Exception e) {
			/* --------------------------------------------- */
			e.printStackTrace();
			/* --------------------------------------------- */
		}
		return null;
		/* ================================================== */
	}
	
	
	/* (non-Javadoc)
	 * @see lu.tudor.santec.gecamed.prescription.ejb.session.interfaces.PrescriptionManager#getPrescriptionByIncidentId(java.lang.Integer)
	 */
	@SuppressWarnings("unchecked")
	@RolesAllowed("gecam")
	public List<Prescription> getPrescriptionByIncidentId(Integer id) {
		/* ============================================= */
		if (id == null)
			return null;
		/* ------------------------------------------------------ */
		try {
			List<Prescription> result = em.createNamedQuery(
					Prescription.GET_PRESCRIPTION_BY_INCIDENT_ID)
					.setParameter("incidentId", id)
					.getResultList();
			return result;
		} catch (Exception e) {
			return null;
		}

		/* ============================================= */
	}
	
	
	/**
	 * @param patientId
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public List<Prescription> getPrescriptions(Integer patientId) {
		/* ================================================== */
		if (patientId == null)
			return null;
		/* ------------------------------------------------------- */
		Query q = em.createQuery("SELECT OBJECT(o) FROM Prescription o " +
									"WHERE o.incidentEntryId IN (" +
									"SELECT e.id FROM IncidentEntry e " +
														"WHERE e.incidentId IN (SELECT i.id FROM Incident i " +
																				"WHERE i.patientId = :patientId)) " +
									"ORDER BY o.incidentEntryId ASC");
		q.setParameter("patientId", patientId);
		try {
			/* --------------------------------------------- */
			return q.getResultList();
			/* --------------------------------------------- */
		} catch (Exception e) {
			/* --------------------------------------------- */
			e.printStackTrace();
			/* --------------------------------------------- */
		}
		return null;
		/* ================================================== */
	}
	
	

	public void deleteTemplates(List<PrescriptionTemplate> templates) {
		/* ============================================= */
		if (templates != null) {
			Query q = em.createQuery("SELECT OBJECT(o) FROM PrescriptionTemplate o" +
										" WHERE o.id = :id");
			for (PrescriptionTemplate t : templates) {
				// hier gehts weiter. Templates löschen!!!
				// make the lookup for the template
				q.setParameter("id", t.getId());
				em.remove(q.getSingleResult());
			}
		}
		/* ============================================= */
	}

	public void deletePosologyTemplate(PosologyTemplate template) {
		/* ============================================= */
		if (template != null) {
			em.remove(em.find(PosologyTemplate.class, template.getId()));
		}
		/* ============================================= */
	}

	@SuppressWarnings("unchecked")
	public List<PosologyTemplate> getPosologyTemplates(Integer physicianID) {
		/* ============================================= */
		try {
			/* ------------------------------------------------------ */
			List<PosologyTemplate> result =
				em.createNamedQuery("findAllPosologyTemplatesByPhysicianID")
					.setParameter("physicianID", physicianID)
					.getResultList();
			return result;
			/* ------------------------------------------------------ */
		} catch (Exception e) {
			/* ------------------------------------------------------ */
			e.printStackTrace();
			return new ArrayList<PosologyTemplate>();
			/* ------------------------------------------------------ */
		}
		/* ============================================= */
	}

	public PosologyTemplate savePosologyTemplate(PosologyTemplate template) {
		/* ============================================= */
		if (template != null) {
			/* ------------------------------------------------------ */
			return em.merge(template);
			/* ------------------------------------------------------ */
		}
		return null;
		/* ============================================= */
	}

	/* (non-Javadoc)
	 * @see lu.tudor.santec.gecamed.prescription.ejb.session.interfaces.PrescriptionManager#getPrescription(java.lang.Integer)
	 */
	public Prescription getPrescription(Integer prescId) {
		/* ====================================================== */
		Query q = em.createQuery("SELECT OBJECT(o) FROM Prescription o " +
								"WHERE o.id = :id");
		q.setParameter("id", prescId);
		try {
			/* --------------------------------------------- */
			return (Prescription) q.getSingleResult();
			/* --------------------------------------------- */
		} catch (Exception e) {
			/* --------------------------------------------- */
			e.printStackTrace();
			return null;
			/* --------------------------------------------- */
		}
		/* ====================================================== */
	}
	
	
	public PrescriptionRevision getPrescriptionRevision(Integer revId) {
		/* ====================================================== */
		Query q = em.createQuery("SELECT OBJECT(o) FROM PrescriptionRevision o " +
								"WHERE o.id = :id");
		q.setParameter("id", revId);
		try {
			/* --------------------------------------------- */
			return (PrescriptionRevision) q.getSingleResult();
			/* --------------------------------------------- */
		} catch (Exception e) {
			/* --------------------------------------------- */
			e.printStackTrace();
			return null;
			/* --------------------------------------------- */
		}
		/* ====================================================== */
	}
	
	
	
	public List<Integer> getPrescriptionRevisionIdsToConvert() {
		/* ============================================== */
		// get all MeasurementValues without an IncidentEntry
		/* ------------------------------------------------------- */
		Query q = em.createQuery("SELECT OBJECT(o) FROM PrescriptionRevision o "
				+ "WHERE o.incidentEntryId = null ORDER BY o.incidentId ASC");
		try {
			/* --------------------------------------------- */
			List<PrescriptionRevision> values = q.getResultList();
			List<Integer> idList = new ArrayList<Integer>();
			for (PrescriptionRevision p : values) {
				/* ============================================== */
				idList.add(p.getId());
				/* ============================================== */
			}
			return idList;
			/* ---------------------------------------------------- */
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
		/* ============================================== */
	}
	
	
	/**
	 * Adds an IncidentEntry object to PrescriprionRevisions.
	 * Must be done only once per installation and only if the installation
	 * was made before the switch to flexi IncidentEntry.
	 * 
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public boolean convertPrescriptionRevision(Integer revId) {
		/* ================================================== */
		// get all PrescriptionRevisions without an IncidentEntry
		/* ------------------------------------------------------- */
//		Query q = em.createQuery("SELECT OBJECT(o) FROM PrescriptionRevision o " +
//									"WHERE o.incidentEntryId = null ORDER BY o.incidentId ASC");
		try {
			/* --------------------------------------------- */
//			List<PrescriptionRevision> values = q.getResultList();
//			if (values == null || values.size() < 1)
//				return true;
			/* ------------------------------------------------------- */
			// Create a HashMap to store the Entrys by the incident id
			/* ------------------------------------------------------- */
//			HashMap<Integer, Prescription> prescriptions = new HashMap<Integer, Prescription>();
			
			/* ------------------------------------------------------- */
			// for each prescription revision, do a lookup of the
			// prescription object and copy the incidentEntry
			/* ------------------------------------------------------- */
			Prescription currentPrescription = null;
			System.out.println("RevisionConvert " + revId);
//			for (PrescriptionRevision rev : values) {
			PrescriptionRevision rev = getPrescriptionRevision(revId);
				/* ------------------------------------------------------- */
				// get tha fitting prescription
				/* ------------------------------------------------------- */
//				currentPrescription = prescriptions.get(rev.getPrescriptionId());
				/* ------------------------------------------------------- */
				// if not yet in the hash, load it from the database
				/* ------------------------------------------------------- */
				if (currentPrescription == null) {
					/* ------------------------------------------------------- */
					currentPrescription = getPrescription(rev.getPrescriptionId());
//					prescriptions.put(currentPrescription.getId(), currentPrescription);
					/* ------------------------------------------------------- */
				}
				/* ------------------------------------------------------- */
				rev.setIncidentEntry(currentPrescription.getIncidentEntry());
				rev.setIncidentEntryId(currentPrescription.getIncidentEntryId());
				/* ------------------------------------------------------- */
				em.merge(rev);
				/* ------------------------------------------------------- */
//			}
			/* --------------------------------------------- */
		} catch (Exception e) {
			/* --------------------------------------------- */
			e.printStackTrace();
			return false;
			/* --------------------------------------------- */
		}
		
		return true;
		/* ================================================== */
	}
	
	
	
	

//	/**
//	 * Adds an IncidentEntry object to PrescriprionRevisions.
//	 * Must be done only once per installation and only if the installation
//	 * was made before the switch to flexi IncidentEntry.
//	 * 
//	 * @return
//	 */
//	@SuppressWarnings("unchecked")
//	public boolean convertPrescriptionRevisions() {
//		/* ================================================== */
//		// get all PrescriptionRevisions without an IncidentEntry
//		/* ------------------------------------------------------- */
//		Query q = em.createQuery("SELECT OBJECT(o) FROM PrescriptionRevision o " +
//									"WHERE o.incidentEntryId = null ORDER BY o.incidentId ASC");
//		try {
//			/* --------------------------------------------- */
//			List<PrescriptionRevision> values = q.getResultList();
//			if (values == null || values.size() < 1)
//				return true;
//			/* ------------------------------------------------------- */
//			// Create a HashMap to store the Entrys by the incident id
//			/* ------------------------------------------------------- */
//			HashMap<Integer, Prescription> prescriptions = new HashMap<Integer, Prescription>();
//			
//			/* ------------------------------------------------------- */
//			// for each prescription revision, do a lookup of the
//			// prescription object and copy the incidentEntry
//			/* ------------------------------------------------------- */
//			Prescription currentPrescription = null;
//			for (PrescriptionRevision rev : values) {
//				/* ------------------------------------------------------- */
//				// get tha fitting prescription
//				/* ------------------------------------------------------- */
//				currentPrescription = prescriptions.get(rev.getPrescriptionId());
//				/* ------------------------------------------------------- */
//				// if not yet in the hash, load it from the database
//				/* ------------------------------------------------------- */
//				if (currentPrescription == null) {
//					/* ------------------------------------------------------- */
//					currentPrescription = getPrescription(rev.getPrescriptionId());
//					prescriptions.put(currentPrescription.getId(), currentPrescription);
//					/* ------------------------------------------------------- */
//				}
//				/* ------------------------------------------------------- */
//				rev.setIncidentEntry(currentPrescription.getIncidentEntry());
//				rev.setIncidentEntryId(currentPrescription.getIncidentEntryId());
//				/* ------------------------------------------------------- */
//				em.merge(rev);
//				/* ------------------------------------------------------- */
//			}
//			/* --------------------------------------------- */
//		} catch (Exception e) {
//			/* --------------------------------------------- */
//			e.printStackTrace();
//			return false;
//			/* --------------------------------------------- */
//		}
//		
//		return true;
//		/* ================================================== */
//	}
	
	
	
	/**
	 * Returns all prescription templates of type medicin
	 * 
	 * @return
	 */
	public List<PrescriptionTemplate> getAllTemplates4Convertion() {
		/* ================================================== */
		Query q = em.createQuery("SELECT OBJECT(o) FROM PrescriptionTemplate o " +
									"WHERE o.prescriptionTypeId IN (" +
										"SELECT p.id FROM PrescriptionType p WHERE p.name = :type)");
		q.setParameter("type", PrescriptionType.MEDICINE);
		
		try {
			/* --------------------------------------------- */
			return q.getResultList();
			/* --------------------------------------------- */
		} catch (Exception e) {
			/* --------------------------------------------- */
			e.printStackTrace();
			return null;
			/* --------------------------------------------- */
		}
		/* ================================================== */
	}

	public void convert_1_0_9_PrescriptionTemplate(PrescriptionTemplate t) {
		/* ====================================================== */
		if (t == null)
			return;
		info("Start converting prescription template " + t.getId());
		/* ------------------------------------------------------- */
		// check if text content is empty, if so, return
		/* ------------------------------------------------------- */
		if (t.getTextContent() != null && !"".equals(t.getTextContent().trim())) {
			info("Nothing to do for prescription template " + t.getId());
			return;
		}
		/* ------------------------------------------------------- */
		if (t.getTemplateDrugs() != null &&
				t.getTemplateDrugs().size() > 0) {
			/* ------------------------------------------------------ */
			StringBuffer buff = new StringBuffer();
			for (TemplateDrug drug : t.getTemplateDrugs()) {
				/* ------------------------------------------------------ */
				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");
				/* ------------------------------------------------------ */
			}
			t.setTextContent(buff.toString());
			info("Finished converting prescription template " + t.getId());
			/* ------------------------------------------------------ */
		}
		info("Saving prescription template " + t.getId());
		em.merge(t);
		info("Done saving template " + t.getId());
		/* ====================================================== */
	}
	
	
	/**
	 * Returns all prescriptions of type medicine to convert
	 * 
	 * @param start
	 * @param pageSize
	 * @return
	 */
	public List<Prescription> getAllPrescription4Convert(Integer start, Integer pageSize) {
		/* ================================================== */
		Query q = em.createQuery("SELECT OBJECT(o) FROM Prescription o " +
				"WHERE o.prescriptionTypeId IN (" +
					"SELECT p.id FROM PrescriptionType p WHERE p.name = :type)");
		q.setParameter("type", PrescriptionType.MEDICINE);
		
		
		q.setFirstResult(start);
		q.setMaxResults(pageSize);
		
		try {
		/* --------------------------------------------- */
		return q.getResultList();
		/* --------------------------------------------- */
		} catch (Exception e) {
		/* --------------------------------------------- */
		e.printStackTrace();
		return null;
		/* --------------------------------------------- */
		}
		/* ================================================== */
	}
	
	/**
	 * Returns all prescriptions witch have no the same incident id like there incident entry 
	 * 
	 * @return List of prescriptions
	 */
	public List<Integer> getPrescriptionsNoSyncWithIncidentEntry() {
		
		// select only prescriptions witch have no the same incident id like there incident entry
		logger.info("get Prescription witch have no the same incident id like there incident entry ...");
	    long startTime = System.currentTimeMillis();
		
	    List<Integer> prescriptionList = em.createQuery(
				"SELECT p.id " +
				"FROM Prescription p, IncidentEntry ie " +
				"WHERE p.incidentEntryId = ie.id " +
				"AND p.incidentId != ie.incidentId"
				).getResultList();
	    
		logger.info("get all Prescription took " + (System.currentTimeMillis()-startTime)/1000 + " sec.");		
		return prescriptionList;
	}
}
