/*****************************************************************************
 *                                                                           *
 *  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.patient.gui.history;

import java.awt.Component;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;

import javax.swing.Action;
import javax.swing.JPopupMenu;
import javax.swing.JTable;
import javax.swing.table.TableCellRenderer;

import lu.tudor.santec.gecamed.core.gui.listener.IEntryPrintRenderer;
import lu.tudor.santec.gecamed.core.gui.listener.IEntryTypeHandler;
import lu.tudor.santec.gecamed.core.gui.plugin.filehandler.DefaultEntryDeleteAction;
import lu.tudor.santec.gecamed.core.gui.utils.LineColorCellRenderer;
import lu.tudor.santec.gecamed.core.gui.utils.StringHelper;
import lu.tudor.santec.gecamed.core.utils.ManagerFactory;
import lu.tudor.santec.gecamed.patient.ejb.entity.beans.IncidentEntry;
import lu.tudor.santec.gecamed.patient.ejb.entity.beans.MeasurementValue;
import lu.tudor.santec.gecamed.patient.ejb.session.beans.IncidentManagerBean;
import lu.tudor.santec.gecamed.patient.ejb.session.interfaces.IncidentManager;
import lu.tudor.santec.gecamed.patient.gui.PatientManagerModule;
import lu.tudor.santec.gecamed.patient.gui.history.table.HistoryTableModel;
import lu.tudor.santec.gecamed.patient.gui.settings.ConsultationEntryConfig;
import lu.tudor.santec.gecamed.patient.gui.settings.PatientModuleSettings;
import lu.tudor.santec.i18n.Translatrix;

/**
 * Handler for the SOAP IncidentEntryTypes
 * 
 * @author martin.heinemann@tudor.lu
 * 04.03.2008
 * 10:36:20
 *
 *
 * @version
 * <br>$Log: MeasurementHandler.java,v $
 * <br>Revision 1.11  2013-09-04 15:33:26  troth
 * <br>The new consultation view with more entries and the sickleave version 2 history view work now.
 * <br>
 * <br>Revision 1.10  2013-02-05 13:15:18  ferring
 * <br>letter status added
 * <br>
 * <br>Revision 1.9  2010-11-30 13:26:27  troth
 * <br>Complete - # 642: Unregelm�ssige Formatierung der Measurment Eintr�ge in der Historie
 * <br>http://santec.tudor.lu/trac/gecamed/ticket/642
 * <br>
 * <br>Revision 1.8  2010-09-20 13:38:37  troth
 * <br>add delete function on (right-click) history popupmenu for S.O.A.P. entries and measurements
 * <br>
 * <br>Revision 1.7  2009-05-06 15:58:51  heinemann
 * <br>added method to generate printable output of the incident entrys
 * <br>
 * <br>Revision 1.6  2008-09-25 09:43:07  heinemann
 * <br>fixed copyrights
 * <br>
 * <br>Revision 1.5  2008-07-03 11:59:57  heinemann
 * <br>*** empty log message ***
 * <br>
 * <br>Revision 1.4  2008-04-09 09:39:43  heinemann
 * <br>*** empty log message ***
 * <br>
 * <br>Revision 1.3  2008-03-20 16:08:14  heinemann
 * <br>*** empty log message ***
 * <br>
 * <br>Revision 1.2  2008-03-10 12:37:52  heinemann
 * <br>*** empty log message ***
 * <br>
 * <br>Revision 1.1  2008-03-06 15:34:27  heinemann
 * <br>*** empty log message ***
 * <br>
 *   
 */
public class MeasurementHandler implements IEntryTypeHandler, IEntryPrintRenderer{

	
	
	
	static {
		/* ------------------------------------------------------- */
		/* ------------------------------------------------------- */
	}
	
	private MeasurementRenderer renderer = new MeasurementRenderer();
	
	private DefaultEntryDeleteAction deleteAction;
	
	public MeasurementHandler() {
		this.deleteAction = new DefaultEntryDeleteAction(
				Translatrix.getTranslationString("patient.incident.measurement.buttons.delete"),
				Translatrix.getTranslationString("patient.incident.measurement.deleteDialog.title"),
				Translatrix.getTranslationString("patient.incident.measurement.deleteDialog.text")
				);
	}
	
	
	/* (non-Javadoc)
	 * @see lu.tudor.santec.gecamed.core.gui.listener.IEntryTypeHandler#getRenderer(java.lang.String)
	 */
	public TableCellRenderer getRenderer(String entryType) {
		/* ====================================================== */
		return renderer;
		/* ====================================================== */
	}

	public HashMap<Integer, Object> getSpecialEntries(String entryType, Integer patientId) {
		/* ====================================================== */
		// get all values from the server
		/* ------------------------------------------------------- */
		try {
			/* --------------------------------------------- */
			IncidentManager manager = (IncidentManager) ManagerFactory.getRemote(IncidentManagerBean.class);
			/* ------------------------------------------------------- */
			// get the values
			/* ------------------------------------------------------- */
			List<MeasurementValue> values = manager.getMeasurments(patientId);
			/* ------------------------------------------------------- */
			
			HashMap<Integer, Object> historyelements = new HashMap<Integer, Object>();
			if (values != null && values.size() > 0) {
				int count = 0;
				DecimalFormat dFormater = new DecimalFormat();
				Double bmi = 0.0;
				Double hei = 0.0;
				Double wei = 0.0;
				
				Integer lastEntry = null;
				for (MeasurementValue mess : values) {
					/* ------------------------------------------------------- */
					
					// reset collected values if incidentEntry changed.
					Integer incidentEntryID = mess.getIncidentEntryId();
					if (incidentEntryID != null && ! incidentEntryID.equals(lastEntry)) {
						bmi = 0.0;
						hei = 0.0;
						wei = 0.0;
					}
					lastEntry = incidentEntryID;
					
					String valueString = (String) historyelements.get(incidentEntryID);
					if (valueString == null) {
						valueString = "<table style=\"font-family:Arial;font-size:9px;\"><tr valign=\"top\"><td width=\"120\">"+mess.toHTMLString();
						historyelements.put(incidentEntryID, valueString);
						count = 1;
					} else {
						if (count%3 == 0)
							valueString += mess.toHTMLString();
						else
							valueString += "\n" + mess.toHTMLString();
						count ++;
						if (count%3 == 0)
							valueString += "</td><td width=\"120\">";
						historyelements.put(incidentEntryID, valueString);	
					}
					
					// if required measurement height and weight are set print out bmi in history
					if(mess.getMeasurementType().getAlias().equals("HEI"))
						hei = mess.getValueNumeric();
					if(mess.getMeasurementType().getAlias().equals("WEI"))
						wei = mess.getValueNumeric();
					
					if(hei != 0.0 && wei != 0.0)
					{
						bmi = wei / ( hei * hei );
						if (count%3 == 0)
							valueString += "<b>" + Translatrix.getTranslationString("patient.incident.measurement.bmi") + " " + dFormater.format(bmi) + "</b> kg/m\u00B2";
						else
							valueString += "\n<b>" + Translatrix.getTranslationString("patient.incident.measurement.bmi") + " " + dFormater.format(bmi) + "</b> kg/m\u00B2";
						count++;
						if (count%3 == 0)
							valueString += "</td><td width=\"120\">";
						historyelements.put(incidentEntryID, valueString);
						
						// reset wei, hei, bmi
						wei = 0.0;
						hei = 0.0;
						bmi = 0.0;
					}
					/* ------------------------------------------------------- */
				}
			}
			return historyelements;
			/* --------------------------------------------- */
		} catch (Exception e) {
			/* --------------------------------------------- */
			e.printStackTrace();
			/* --------------------------------------------- */
		}
		return null;
		/* ====================================================== */
	}

	
	/**
	 * @author martin.heinemann@tudor.lu
	 * 04.03.2008
	 * 10:46:21
	 *
	 *
	 * @version
	 * <br>$Log: MeasurementHandler.java,v $
	 * <br>Revision 1.11  2013-09-04 15:33:26  troth
	 * <br>The new consultation view with more entries and the sickleave version 2 history view work now.
	 * <br>
	 * <br>Revision 1.10  2013-02-05 13:15:18  ferring
	 * <br>letter status added
	 * <br>
	 * <br>Revision 1.9  2010-11-30 13:26:27  troth
	 * <br>Complete - # 642: Unregelm�ssige Formatierung der Measurment Eintr�ge in der Historie
	 * <br>http://santec.tudor.lu/trac/gecamed/ticket/642
	 * <br>
	 * <br>Revision 1.8  2010-09-20 13:38:37  troth
	 * <br>add delete function on (right-click) history popupmenu for S.O.A.P. entries and measurements
	 * <br>
	 * <br>Revision 1.7  2009-05-06 15:58:51  heinemann
	 * <br>added method to generate printable output of the incident entrys
	 * <br>
	 * <br>Revision 1.6  2008-09-25 09:43:07  heinemann
	 * <br>fixed copyrights
	 * <br>
	 * <br>Revision 1.5  2008-07-03 11:59:57  heinemann
	 * <br>*** empty log message ***
	 * <br>
	 * <br>Revision 1.4  2008-04-09 09:39:43  heinemann
	 * <br>*** empty log message ***
	 * <br>
	 * <br>Revision 1.3  2008-03-20 16:08:14  heinemann
	 * <br>*** empty log message ***
	 * <br>
	 * <br>Revision 1.2  2008-03-10 12:37:52  heinemann
	 * <br>*** empty log message ***
	 * <br>
	 * <br>Revision 1.1  2008-03-06 15:34:27  heinemann
	 * <br>*** empty log message ***
	 * <br>
	 *   
	 */
	class MeasurementRenderer extends LineColorCellRenderer {

		/**
		 * 
		 */
		private static final long serialVersionUID = 1L;
		
		private final static int fontSize = 9;
		
		/* (non-Javadoc)
		 * @see lu.tudor.santec.gecamed.core.gui.utils.LineColorCellRenderer#getTableCellRendererComponent(javax.swing.JTable, java.lang.Object, boolean, boolean, int, int)
		 */
		@Override
		public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
			/* ====================================================== */
			if (value instanceof IncidentEntry) {
				/* ------------------------------------------------------- */
				IncidentEntry entry = (IncidentEntry) value;
				if (column == 2) {
					/* ------------------------------------------------------- */
//					return super.getTableCellRendererComponent(table, "<html><b>Ms</b>", isSelected,
//							hasFocus, row, column);
					
					// get the acronym for the entry
					ConsultationEntryConfig entryConfig	= null;
					PatientModuleSettings patientGlobalSettings = PatientManagerModule.getInstance().patientSettings;
					
					entryConfig = new ConsultationEntryConfig((String) patientGlobalSettings.getValue(entry.getEntryType().getName()));
					
					return super.getTableCellRendererComponent(table, entryConfig.getAcronym(), isSelected,
							hasFocus, row, column);
					/* ------------------------------------------------------- */
				} else
					if (column == 3) {
						/* ------------------------------------------------------- */
						HistoryTableModel model = (HistoryTableModel) table.getModel();
//						IncidentEntry entry = (IncidentEntry) value;
						/* ------------------------------------------------------- */
						Object o = model.getSpecialEntry(entry.getId());
						String text = null;
						
						if (o instanceof String)
							text = (String) o;
						/* ------------------------------------------------------- */
						String s = "";
						/* -------------------------------------------ENTRY_TYPE------------ */
						if (text != null)
							s = ("<html><span style=\"font-family:Arial;font-size:"
									+ fontSize + "px;\">"
									+ text.replaceAll("\n", "<br>"));
						
						setSize(table.getColumnModel().getColumn(column).getWidth(),
								getPreferredSize().height);

						if (table.getRowHeight(row) < getPreferredSize().height) {
							table.setRowHeight(row, getPreferredSize().height);
						}
						
						
						return super.getTableCellRendererComponent(table, s, isSelected,
								hasFocus, row, column);
						/* ------------------------------------------------------- */
					}
				/* ------------------------------------------------------- */
			}
			
			return super.getTableCellRendererComponent(table, value, isSelected,
					hasFocus, row, column);
			/* ====================================================== */
		}
	}


	public Collection<Action> getActions(IncidentEntry entry) {		
		List<Action> actions = new ArrayList<Action>();

		this.deleteAction.setEntry(entry);
		actions.add(this.deleteAction);

		return actions;
	}
	
	
	public JPopupMenu getPopup(IncidentEntry entry)
	{
		return null;
	}


	public boolean openEntry(IncidentEntry entry) {
		/* ====================================================== */
		PatientManagerModule.getInstance().getPatientPanel().openConsultation(entry);
		return true;
		/* ====================================================== */
	}


	public IEntryPrintRenderer getPrintRenderer(String entryType) {
		/* ====================================================== */
		return this;
		/* ====================================================== */
	}


	public String renderPrintEntry(IncidentEntry entry) {
		/* ====================================================== */
		if (entry == null)
			return "";
		/* ------------------------------------------------------- */
		// get all measurement values for this entry
		/* ------------------------------------------------------- */
		try {
			/* --------------------------------------------- */
			IncidentManager manager = (IncidentManager) ManagerFactory.getRemote(IncidentManagerBean.class);
			
			List<MeasurementValue> values = manager.getMeasurementsByIncidentEntry(entry.getId());
			if (values != null) {
				/* ------------------------------------------------------- */
				int count = 0;
				StringBuffer buff = new StringBuffer();
				/* ------------------------------------------------------- */
				// add a new line for the measurements
				/* ------------------------------------------------------- */
				buff.append(StringHelper.NEWLINE);
				buff.append(Translatrix.getTranslationString("patient.incident.measurement")+": ");
				buff.append(StringHelper.NEWLINE);
				/* ------------------------------------------------------- */
				// iterate over all values and build a pseude table with 3 columns
				/* ------------------------------------------------------- */
				for (MeasurementValue value : values) {
					/* ------------------------------------------------------- */
					buff.append(value.toString());
					count ++;
					/* ------------------------------------------------------- */
					// after the third entry in a row, add a newline
					/* ------------------------------------------------------- */
					if (count%3 == 0)
						buff.append(StringHelper.NEWLINE);
					else
						buff.append(StringHelper.TAB);
					/* ------------------------------------------------------- */
				}
				buff.append(StringHelper.NEWLINE);
				return buff.toString();
				/* ------------------------------------------------------- */
			}
			/* --------------------------------------------- */
		} catch (Exception e) {
			/* --------------------------------------------- */
			e.printStackTrace();
			/* --------------------------------------------- */
		}
		return null;
		/* ====================================================== */
	}

}
