package lu.tudor.santec.gecamed.core.gui.updates;

import java.util.List;

import lu.tudor.santec.gecamed.core.gui.MainFrame;
import lu.tudor.santec.gecamed.core.utils.ManagerFactory;
import lu.tudor.santec.gecamed.core.utils.VersionUtils;
import lu.tudor.santec.gecamed.prescription.ejb.entity.beans.Prescription;
import lu.tudor.santec.gecamed.prescription.ejb.entity.beans.PrescriptionDrug;
import lu.tudor.santec.gecamed.prescription.ejb.entity.beans.PrescriptionTemplate;
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;

/**
 * @author martin.heinemann@tudor.lu
 * 18.12.2008
 * 10:17:27
 *
 *
 * @version
 * <br>$Log: UpdatePrescription1_0_9.java,v $
 * <br>Revision 1.4  2013-12-27 18:09:26  donak
 * <br>Cleanup of imports
 * <br>
 * <br>Revision 1.3  2013-07-15 06:18:37  ferring
 * <br>logging changed
 * <br>
 * <br>Revision 1.2  2008-12-22 10:01:43  heinemann
 * <br>fixed blocking of glasspane, even when the prescription update does not need to run
 * <br>
 * <br>Revision 1.1  2008-12-18 10:55:50  heinemann
 * <br>finished update method for prescription module
 * <br>
 *   
 */
public class UpdatePrescription1_0_9 implements IGECAMedUpdate{
	
	/** the logger Object for this class */
	private static Logger logger = Logger.getLogger(UpdatePrescription1_0_9.class.getName());
	
	/**
	 * 
	 */
	public UpdatePrescription1_0_9() {
		/* ================================================== */

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

	public boolean check() {
		/* ====================================================== */
		String version    = MainFrame.getInstance().getCurrentVersion();
		String updateDone = MainFrame.getInstance().getInfo(MainFrame.INFO_PRESCRIPTION_UPDATE);
		/* ------------------------------------------------------- */
		// cancel if the current version is newer or equal than 1.0.9
		/* ------------------------------------------------------- */
		if ((version != null && !VersionUtils.isSmaller(version, "1.0.9")) || (updateDone != null && updateDone.equals("true")))
			return false;
		return true;
		/* ====================================================== */
	}

	/**
	 * Updates to the new prescription module that uses plain text only
	 * We need to convert the old prescription module and convert
	 * old medicin 
	 */
	public void doUpdate() {
		/* ====================================================== */
		String version    = MainFrame.getInstance().getCurrentVersion();
		String updateDone = MainFrame.getInstance().getInfo(MainFrame.INFO_PRESCRIPTION_UPDATE);
		/* ------------------------------------------------------- */
		// cancel if the current version is newer or equal than 1.0.9
		/* ------------------------------------------------------- */
		if ((version != null && !VersionUtils.isSmaller(version, "1.0.9")) || (updateDone != null && updateDone.equals("true")))
			return;
		/* ------------------------------------------------------- */
		
		/* ------------------------------------------------------- */
		// first update the prescription templates.
		// 
		// we just have to care about the medicin type templates. We must copy the
		// prescription drug infos to the text_content field of the prescription.
		// prescription drug is obsolete.
		/* ------------------------------------------------------- */
		logger.info("Start converting prescription templates");
		try {
			/* --------------------------------------------- */
			PrescriptionManager pManager = (PrescriptionManager) ManagerFactory.getRemote(PrescriptionManagerBean.class);
			
			List<PrescriptionTemplate> templates = pManager.getAllTemplates4Convertion();
			if (templates != null) {
				/* ------------------------------------------------------- */
				logger.info("Converting an amount of " + templates.size() + " of prescription templates.");
				
				// convert each template. We do it in that way to prevent 
				// transaction timeout of the session bean
				for (PrescriptionTemplate t: templates) {
					/* ------------------------------------------------------- */
					logger.info("Converting template " + t.getId());
					pManager.convert_1_0_9_PrescriptionTemplate(t);
					logger.info("Finish converting template " + t.getId());
					/* ------------------------------------------------------- */
				}
				/* ------------------------------------------------------- */
			}
			logger.info("Finished converting prescription template");
			logger.info("===============================================================");	
			logger.info(" ");
			logger.info("Start converting prescriptions");
			int startPos = 0;
			int pageSize = 50;
			List<Prescription> prescriptions = null;
			/* ------------------------------------------------------- */
			// fetch 50 prescriptions and convert them into textContent
			/* ------------------------------------------------------- */
			do {
				/* ------------------------------------------------------- */
				logger.info("Fetching next set of prescription ["+startPos+","+(startPos+pageSize)+"]....");
				prescriptions = pManager.getAllPrescription4Convert(startPos, pageSize);
				/* ------------------------------------------------------- */
				logger.info("Converting "+prescriptions.size() + " prescriptions");
				
				if (prescriptions != null)
					for (Prescription p : prescriptions) {
						/* ------------------------------------------------------- */
						if (p.getPrescriptionDrugs() != null &&
								p.getPrescriptionDrugs().size() > 0) {
							/* ------------------------------------------------------ */
							logger.info("Converting prescription " + p.getId());
							StringBuffer buff = new StringBuffer();
							for (PrescriptionDrug drug : p.getPrescriptionDrugs()) {
								/* ------------------------------------------------------ */
								buff.append(drug.getName()+"\n");
								buff.append((drug.getPosology() != null && !"".equals(drug.getPosology().trim())) ? drug.getPosology()+"\n\n" :"\n");
								/* ------------------------------------------------------ */
							}
							p.setTextContent(buff.toString());
							
							pManager.savePrescription(p);
							logger.info("Saving prescription " + p.getId());
						/* ------------------------------------------------------- */
						} else
						logger.info("Skipping prescription " + p.getId() +". Owns no drugs!");
					}
				/* ------------------------------------------------------- */
				startPos += pageSize;
				/* ------------------------------------------------------- */
			} while (prescriptions != null && prescriptions.size() > 0);
			logger.info("Converting of prescriptions done. Ready to go ahead");
			logger.info("===============================================================");	
			logger.info(" ");
			
			MainFrame.getInstance().setInfo(MainFrame.INFO_PRESCRIPTION_UPDATE, "true");
			/* --------------------------------------------- */
		} catch (Exception e) {
			/* --------------------------------------------- */
			e.printStackTrace();
			/* --------------------------------------------- */
		}
		/* ================================================== */
	}

}
