package lu.tudor.santec.gecamed.prescription.gui.util;

import java.util.Date;
import java.util.HashSet;
import java.util.List;

import javax.swing.JDialog;

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.core.ejb.entity.beans.PhoneType;
import lu.tudor.santec.gecamed.core.gui.GECAMedLists;
import lu.tudor.santec.gecamed.core.gui.MainFrame;
import lu.tudor.santec.gecamed.core.utils.ManagerFactory;
import lu.tudor.santec.gecamed.core.utils.printing.ireport.UtilFormatter;
import lu.tudor.santec.gecamed.office.ejb.entity.beans.Physician;
import lu.tudor.santec.gecamed.patient.ejb.entity.beans.Incident;
import lu.tudor.santec.gecamed.patient.ejb.entity.beans.Patient;
import lu.tudor.santec.gecamed.prescription.ejb.entity.beans.Prescription;
import lu.tudor.santec.gecamed.prescription.ejb.entity.beans.PrescriptionType;
import lu.tudor.santec.gecamed.prescription.ejb.entity.beans.PrintPrescription;
import lu.tudor.santec.gecamed.prescription.ejb.session.beans.PrescriptionManagerBean;
import lu.tudor.santec.gecamed.prescription.ejb.session.interfaces.PrescriptionManager;

import org.apache.log4j.Logger;

/**
 * Utility class for prescription module
 * 
 * 
 * @author martin.heinemann@tudor.lu
 * 08.12.2008
 * 15:15:10
 *
 *
 * @version
 * <br>$Log: PrescriptionUtils.java,v $
 * <br>Revision 1.13  2013-12-27 18:09:27  donak
 * <br>Cleanup of imports
 * <br>
 * <br>Revision 1.12  2013-07-15 06:18:39  ferring
 * <br>logging changed
 * <br>
 * <br>Revision 1.11  2013-02-19 12:07:34  ferring
 * <br>GECAMedLists changed. Will now automatically load list of all beans
 * <br>
 * <br>Revision 1.10  2012-01-24 10:14:38  ferring
 * <br>unneeded import removed
 * <br>
 * <br>Revision 1.9.2.1  2012-01-20 09:13:54  ferring
 * <br>BRANCHED VERSION
 * <br>
 * <br>Revision 1.9  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.8  2010-10-04 12:39:34  troth
 * <br>Complete - # 562: Diskrepanz zwischen verschreibendem Arzt in DB und auf dem Verschreibungsausdruck
 * <br>http://santec.tudor.lu/trac/gecamed/ticket/562
 * <br>
 * <br>Revision 1.7  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.6  2010-07-19 15:15:35  troth
 * <br>#557: add caisse de maladie to the prescription printout
 * <br>http://santec.tudor.lu/trac/gecamed/ticket/557
 * <br>
 * <br>Revision 1.5  2009-04-15 13:30:50  heinemann
 * <br>*** empty log message ***
 * <br>
 * <br>Revision 1.4  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.3  2009-01-15 13:37:51  heinemann
 * <br>expiry date is now printed, if set
 * <br>
 * <br>Revision 1.2  2008-12-17 15:23:06  heinemann
 * <br>initial commit after merging of branch new prescription
 * <br>
 * <br>Revision 1.1.2.1  2008-12-15 14:08:21  heinemann
 * <br>*** empty log message ***
 * <br>
 *   
 */
public class PrescriptionUtils {
	
	/** the logger Object for this class */
	private static Logger logger = Logger.getLogger(PrescriptionUtils.class.getName());
	
	private static UtilFormatter formatter = new UtilFormatter((AddressManagerInterface) ManagerFactory.getRemote(AddressManagerBean.class));

	static {
		try {
			formatter.setReferenceAddress(MainFrame.getCurrentOffice().getLatestOfficeAddress());
		} catch (Exception e) {
		}
	}
	
	/**
	 *
	 * Print the current Prescription and save the incident, the prescription
	 * and the PrescriptionPrint
	 *
	 * @param incidentForPrescription
	 */
	public static boolean printPrescription(Incident incident, Prescription p) {
		/* ================================================== */
		return printPrescription(incident, p, null);
		/* ================================================== */
	}
	
	/**
	 *
	 * Print the current Prescription and save the incident, the prescription
	 * and the PrescriptionPrint
	 *
	 * @param incident the incident for the prescription. The accident data from the incident is used for the prescription.<br>
	 * attention, will override the prescription accident data!  
	 * @param p
	 * @param parent jdialog, parent of the possibly upcoming print preview dialog
	 * @return
	 */
	public static boolean printPrescription(Incident incident, Prescription p, JDialog parent) {
		/* ============================================= */
		// as prescriptions can not be modified, we mustn't check
		// whether the prescriptions is persistant or not
		// just do it =)
		if (incident != null && incident.isPersistent()) {
			/* ------------------------------------------------------ */
			// get the appropriate prescription
			// Prescription p = model.getCurrentPrescriptionForPrint(
			// currentPatient);
			if (p == null)
				return false;
			p.setIncidentId(incident.getId());
			/* ------------------------------------------------------- */
//			// add accident data
//			p.setAccidentDate(incident.getAccidentDate());
//			p.setAccidentNr(incident.getAccidentNr());

			/* ------------------------------------------------------ */
			Prescription newPresc = doPrint(p, parent);
			if (newPresc != null) {
				return true;
			}

			/* ------------------------------------------------------ */
		}
		
		return false;
		/* ============================================= */
	}
	
	
	/**
	 * 
	 * Prints a prescription and save the printout
	 * 
	 * @param p
	 * @return the printed prescription object
	 */
	public static Prescription doPrint(Prescription p) {
		/* ================================================== */
		return doPrint(p, null);
		/* ================================================== */
	}
	
	/**
	 * 
	 * Prints a prescription and save the printout
	 * 
	 * @param p
	 * @return the printed prescription object
	 */
	public static Prescription doPrint(Prescription p, JDialog parent) {
		/* ====================================================== */
		//	print
		if (PrescriptionPrinter.print(p, false, (p.getExpiryDate() != null), parent)) {
			/* ------------------------------------------------------ */
			// create PrescriptionPrint object
			PrintPrescription print = new PrintPrescription();

			print.setPrintedById(MainFrame.getCurrentUserId());
			print.setPrintDate(new Date());
			print.setIsCopy(false);
			print.setPrescription(p);
			if (p.getPrintPrescriptions() == null)
				p.setPrintPrescriptions(new HashSet<PrintPrescription>());
			p.getPrintPrescriptions().add(print);
			// and save the Prescription
			Prescription newPresc = getManager().savePrescription(p);

			return newPresc;
			/* ------------------------------------------------------ */
		}
		
		logger.error("Unable to print prescription!!!!");
		return null;
		/* ====================================================== */
	}
	
	/**
	 * 
	 * Prints a prescription and save the printout
	 * 
	 * @param p
	 * @return the printed prescription object
	 */
	public static Prescription doCopyPrint(Prescription p) {
		/* ================================================== */
		return doCopyPrint(p, null);
		/* ================================================== */
	}
	
	
	/**
	 * 
	 * Prints a prescription and save the printout
	 * 
	 * @param p
	 * @return the printed prescription object
	 */
	public static Prescription doCopyPrint(Prescription p, JDialog parent) {
		/* ====================================================== */
		//	print
		if (PrescriptionPrinter.print(p, true, false, parent)) {
			/* ------------------------------------------------------ */
			// create PrescriptionPrint object
			PrintPrescription print = new PrintPrescription();

			print.setPrintedById(MainFrame.getCurrentUserId());
			print.setPrintDate(new Date());
			print.setIsCopy(true);
			print.setPrescription(p);
			if (p.getPrintPrescriptions() == null)
				p.setPrintPrescriptions(new HashSet<PrintPrescription>());
			p.getPrintPrescriptions().add(print);
			// and save the Prescription
			Prescription newPresc = getManager().savePrescription(p);

			return newPresc;
			/* ------------------------------------------------------ */
		}
		
		logger.error("Unable to print prescription!!!!");
		return null;
		/* ====================================================== */
	}
	
	
	
	
	/**
	 * Fill the Prescription object with the patients data
	 *
	 * @param p
	 * @param patient
	 * @param standAlone
	 */
	public  static void fillStaticData(Prescription p, Patient patient) {
		/* ====================================================== */
		// physician stuff
		Physician physician;
		
		// if prescription is a old one physician can not change 
		if(!p.isPersistent()) physician = MainFrame.getCurrentPhysician();
		else {
			physician = MainFrame.getPhysicianById(p.getPhysicianId());
		}
		p.setPhysicianId(physician.getId());
		p.setPhysicianFullName(formatter.formatPhysicianName(physician, true));
		p.setPhysicianUcmCode(physician.getUcmCode());
		p.setPhysicianSpeciality(physician.getSpeciality());

		/* ------------------------------------------------------ */
		// adddress
		p.setPhysicianAddress(formatter.formatPhysicianAddress(physician));
		/* ------------------------------------------------------ */
		// phone
		// if the physician has an own phone, take this,
		// if not, take the one from the office
		/* ------------------------------------------------------- */
		if (physician.getPhoneExtension() != null && !physician.getPhoneExtension().equals("")) {
			p.setPhysicianPhone(physician.getPhoneExtension());
		}
		else {
			/* ------------------------------------------------------- */
			try {
				p.setPhysicianPhone(MainFrame.getCurrentOffice()
					.getOfficePhoneByType(PhoneType.HOME).getNumber());
			} catch (Exception e) {
				p.setPhysicianPhone("");
			}
			/* ------------------------------------------------------- */
		}
		/* ------------------------------------------------------- */
		// fax
		/* ------------------------------------------------------- */
		if (physician.getFax() != null	&& !physician.getFax().equals("")) {
			/* ------------------------------------------------------- */
			p.setPhysicianFax(physician.getFax());
			/* ------------------------------------------------------- */
		}
		else {
			/* ------------------------------------------------------- */
			try {
				p.setPhysicianFax(MainFrame.getCurrentOffice()
						.getOfficePhoneByType(PhoneType.FAX).getNumber());
			} catch (Exception e) {
				p.setPhysicianFax("");
			}
			/* ------------------------------------------------------- */
		}
		/* ------------------------------------------------------- */
		//	gsm
		/* ------------------------------------------------------- */
		if (physician.getGsm() != null) {
			p.setPhysicianGsm(physician.getGsm());
		}
		else {
			p.setPhysicianGsm("");
		}

		/* ------------------------------------------------------ */
		// patient
		p.setPatientName(patient.getSurName());
		p.setPatientFirstName(patient.getFirstName());
		p.setPatientMaidenName(patient.getMaidenName());
		p.setPatientAddress(formatter.formatPatientHomeAddress(patient));
		p.setPatientSocialSecurityNumber(patient.getSocialSecurityNumber());
		/* ------------------------------------------------------ */
	}
	
	
	
	/**
	 *
	 * Returns the PrescriptionType object for the given type string
	 *
	 * @param typeString
	 * @return
	 */
	public static PrescriptionType getTypeForString(String typeString) {
		/* ====================================================== */
		if (getPrescriptionTypes() != null) {
			/* ------------------------------------------------------ */
			for (PrescriptionType t : getPrescriptionTypes()) {
				if (t.getName().equals(typeString))
					return t;
			}
			/* ------------------------------------------------------ */
		}
		return null;
		/* ====================================================== */
	}
	
	
	/**
	 *
	 * Returns the PrescriptionType object for the given type id
	 *
	 * @param typeString
	 * @return
	 */
	public static PrescriptionType getTypeForId(Integer typeId) {
		/* ====================================================== */
		if (getPrescriptionTypes() != null) {
			/* ------------------------------------------------------ */
			for (PrescriptionType t : getPrescriptionTypes()) {
				if (t.getId().equals(typeId))
					return t;
			}
			/* ------------------------------------------------------ */
		}
		return null;
		/* ====================================================== */
	}
	
	
	/**
	 * Returns all available prescriptin types and stores them in 
	 * a GECAMedList
	 * 
	 * @return
	 */
	public static List<PrescriptionType> getPrescriptionTypes() {
		/* ================================================== */
		
		List<PrescriptionType> returnList = GECAMedLists.getListReference(PrescriptionType.class);
		
//		if (returnList == null || returnList.size() < 1) {
//			/* ------------------------------------------------------- */
//			// reload from database
//			/* ------------------------------------------------------- */
//			try {
//				/* --------------------------------------------- */
//				PrescriptionManager pManager = (PrescriptionManager) 
//						ManagerFactory.getRemote(PrescriptionManagerBean.class);
//				returnList = pManager.getPrescriptionTypes();
//				if (returnList != null) {
//					GECAMedLists.storeList(PrescriptionType.class, 
//							returnList.toArray(new PrescriptionType[returnList.size()]));
//					
//				}
//				/* --------------------------------------------- */
//			} catch (Exception e) {
//				/* --------------------------------------------- */
//				e.printStackTrace();
//				/* --------------------------------------------- */
//			}
//			/* ------------------------------------------------------- */
//		}
		return returnList;
		/* ================================================== */
	}

	
	
	/**
	 *
	 * Get a reference to the prescription manager session bean
	 *
	 * @return
	 */
	protected static PrescriptionManager getManager() {
		/* ====================================================== */
		return (PrescriptionManager)
			ManagerFactory.getRemote(PrescriptionManagerBean.class);
		/* ====================================================== */

	}
	
}
