/FileExtraction/Java_unseen/IMS-MAXIMS_openMAXIMS/Source Library/openmaxims_workspace/Nursing/src/ims/nursing/forms/mnainput/Logic.java
//#############################################################################
//#                                                                           #
//#  Copyright (C) <2015>  <IMS MAXIMS>                                       #
//#                                                                           #
//#  This program is free software: you can redistribute it and/or modify     #
//#  it under the terms of the GNU Affero General Public License as           #
//#  published by the Free Software Foundation, either version 3 of the       #
//#  License, or (at your option) any later version.                          # 
//#                                                                           #
//#  This program 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 Affero General Public License for more details.                      #
//#                                                                           #
//#  You should have received a copy of the GNU Affero General Public License #
//#  along with this program.  If not, see <http://www.gnu.org/licenses/>.    #
//#                                                                           #
//#  IMS MAXIMS provides absolutely NO GUARANTEE OF THE CLINICAL SAFTEY of    #
//#  this program.  Users of this software do so entirely at their own risk.  #
//#  IMS MAXIMS only ensures the Clinical Safety of unaltered run-time        #
//#  software that it builds, deploys and maintains.                          #
//#                                                                           #
//#############################################################################
//#EOH
// This code was generated by Vasile Purdila using IMS Development Environment (version 1.20 build 40824.905)
// Copyright (C) 1995-2004 IMS MAXIMS plc. All rights reserved.

package ims.nursing.forms.mnainput;

import ims.nursing.forms.mnainput.GenForm.grdAssessmentRow;
import ims.nursing.forms.mnainput.GenForm.grdScreeningRow;
import ims.coe.vo.RiskAssessment;
import ims.coe.vo.RiskAssessmentCollection;
import ims.coe.vo.RiskDescription;
import ims.nursing.vo.AssessmentComponent;
import ims.nursing.vo.MiniNutritionalAssessment;
import ims.nursing.vo.MiniNutritionalAssessmentDetails;
import ims.nursing.vo.MiniNutritionalAssessmentDetailsCollection;
import ims.coe.vo.MnaEnhancedVo;
import ims.domain.exceptions.DomainInterfaceException;
import ims.domain.exceptions.StaleObjectException;
import ims.domain.exceptions.UniqueKeyViolationException;
import ims.framework.FormName;
import ims.framework.enumerations.DialogResult;
import ims.framework.exceptions.PresentationLogicException;
import ims.framework.utils.Color;
import ims.framework.utils.Date;
import ims.framework.utils.DateTime;
import ims.framework.utils.Time;
import ims.coe.vo.AssessmentEatingAndDrinking;
import ims.core.vo.AuthoringInformationVo;
import ims.core.vo.HcpLiteVo;
import ims.core.vo.MemberOfStaffShortVo;
import ims.core.vo.VSMetrics;
import ims.core.vo.VitalSignsVo;
import ims.core.vo.lookups.VSType;
import ims.core.vo.lookups.VSTypeCollection;

public class Logic extends BaseLogic
{
	protected void onFormOpen() throws ims.framework.exceptions.FormOpenException
	{
		RiskAssessmentCollection risks = form.getGlobalContext().COE.getMNAAssessments();
		if (risks == null)
		{
			engine.showMessage("Could not retrieve the Braden scale Assessments !");
			return;
		}

		try
		{
			VitalSignsVo vitalSigns = domain.getLastMetrics(form.getGlobalContext().Core.getCurrentCareContext());
			if (vitalSigns != null)
			{
				if (vitalSigns.getMetricsIsNotNull() && vitalSigns.getMetrics() != null)
				{
					if(vitalSigns.getMetrics().getHeightValueIsNotNull() && vitalSigns.getMetrics().getHeightValue()!= null)
					form.decHeight().setValue(vitalSigns.getMetrics().getHeightValue());
				}

			}

			
			
		}
		catch (DomainInterfaceException e2)
		{
			engine.showMessage(e2.getMessage());
		}
	

		MiniNutritionalAssessment mna = form.getGlobalContext().COE.getMNARecord();

		form.grdScreening().getRows().clear();
		form.grdAssessment().getRows().clear();

		GenForm.grdScreeningRow rowS;
		GenForm.grdAssessmentRow rowA;
		for (int i = 0; i < risks.size(); i++)
		{
			RiskAssessment risk = risks.get(i);
			rowS = null;
			rowA = null;

			if (risk.getName().length() > 0 && risk.getName().charAt(0) >= 'A' && risk.getName().charAt(0) <= 'F')
			{
				// Screening
				rowS = form.grdScreening().getRows().newRow();
			}
			else if (risk.getName().length() > 0 && risk.getName().charAt(0) >= 'G')
			{
				// Assessment
				rowA = form.grdAssessment().getRows().newRow();
			}

			if (rowS != null)
			{
				rowS.setRisk(risk.getDescription());
				rowS.setBold(true);
				rowS.setBackColor(Color.Beige);
				rowS.setValue(risk.getMultiple().booleanValue() == true ? "Y" : "N");
				rowS.setTooltipForRisk(risk.getDescription());

				for (int j = 0; j < risk.getRiskFactors().size(); j++)
				{
					GenForm.grdScreeningRow child = rowS.getRows().newRow();

					RiskDescription descr = risk.getRiskFactors().get(j);

					child.setRisk(descr.getName());
					child.setValue(descr.getId());
					child.setTooltipForRisk(descr.getName());

					if (mna != null)
					{
						// update mode
						for (int k = 0; k < mna.getAssessmentDetails().size(); k++)
						{
							if (descr.getId().equals(mna.getAssessmentDetails().get(k).getAssessment().toString()))
							{
								child.setSelect(mna.getAssessmentDetails().get(k).getSelect().booleanValue());
								break;
							}
						}
					}
				}

				rowS.setExpanded(true);
			}
			else if (rowA != null)
			{
				rowA.setRisk(risk.getDescription());
				rowA.setBold(true);
				rowA.setBackColor(Color.Beige);
				rowA.setValue(risk.getMultiple().booleanValue() == true ? "Y" : "N");
				rowA.setTooltipForRisk(risk.getDescription());

				for (int j = 0; j < risk.getRiskFactors().size(); j++)
				{
					GenForm.grdAssessmentRow child = rowA.getRows().newRow();

					RiskDescription descr = risk.getRiskFactors().get(j);

					child.setRisk(descr.getName());
					child.setValue(descr.getId());
					child.setTooltipForRisk(descr.getName());

					if (mna != null)
					{
						// update mode
						for (int k = 0; k < mna.getAssessmentDetails().size(); k++)
						{
							if (descr.getId().equals(mna.getAssessmentDetails().get(k).getAssessment().toString()))
							{
								child.setSelect(mna.getAssessmentDetails().get(k).getSelect().booleanValue());
								break;
							}
						}
					}
				}

				rowA.setExpanded(true);
			}
		}

		/*
		 * root_screening.setExpanded(true); root_assessment.setExpanded(true);
		 */
		form.grdScreening().setReadOnly(false);

		if (mna == null)
		{
			form.dteDate().setValue(new Date());
			form.timTime().setValue(new Time());

			if (domain.getMosUser() != null)
				form.txtHcp().setValue(((MemberOfStaffShortVo) domain.getMosUser()).toString());
		}
		else
		{
			form.dteDate().setValue(mna.getDateTimeInitiated().getDate());
			form.timTime().setValue(mna.getDateTimeInitiated().getTime());

			if (mna.getHcpInitiated() != null && mna.getHcpInitiated().getName() != null)
				form.txtHcp().setValue(mna.getHcpInitiated().getName().toString());
		}

		VSMetrics metrics = null;

		if (mna != null && mna.getCareContextIsNotNull())

			/*
			 * WDEV-3838
			 * 
			 * to fix update to MNA
			 * 
			 * 
			 */
			metrics = mna.getMetrics();

		if (metrics != null )
		{
			form.decHeight().setValue(metrics.getHeightValue());

			if (form.getGlobalContext().COE.getMNARecord() != null)
			{
				// update mode
				form.decWeight().setValue(metrics.getWeightValue());
			}
		}

		if (form.getGlobalContext().COE.getMNARecord() != null)
		{
			// update mode
			form.decHeight().setEnabled(false);
			form.decWeight().setEnabled(false);
		}

		float nScoreScreening = getScreeningScore();
		boolean bIsScreeningAnswered = isEverythingAnsweredScreening();

		form.lblTotalScreening().setValue("Screening score: " + String.valueOf(nScoreScreening));
		form.grdAssessment().setReadOnly(nScoreScreening > 11);

		if (bIsScreeningAnswered == false)
			form.grdAssessment().setReadOnly(true);

		form.getLocalContext().setSecondPage(Boolean.FALSE);
		updatePageControls();

		// If there is an associated mobility component for this assessment that
		// is complete
		// we want to disable the save button
		AssessmentComponent comp = form.getGlobalContext().Nursing.getAssessmentComponent();
		if (comp != null && comp.getIsComplete().booleanValue() == true)
		{
			form.btnSave().setEnabled(false);
			form.grdAssessment().setReadOnly(true);
			form.grdScreening().setReadOnly(true);
		}

		// we can update a MNA record which belongs to an EatingDrinking
		// assessment via eating&drinking page only
		if (form.getGlobalContext().COE.getMNARecordIsNotNull() && comp == null)
		{
			Boolean bIsPart = null;

			try
			{
				bIsPart = domain.isPartOfEatingAssessment(form.getGlobalContext().COE.getMNARecord());
			}
			catch (DomainInterfaceException e1)
			{
				engine.showMessage("Error retrieving eating assessment record: " + e1.getMessage());
				return;
			}

			if (bIsPart == Boolean.TRUE)
			{
				form.btnSave().setEnabled(false);
				form.grdAssessment().setReadOnly(true);
				form.grdScreening().setReadOnly(true);
			}
		}
		
		// if width and height are already set and one of BMI grid checkboxes is
		// selected then we disable all BMI grid checkboxes
		disableBMITree();
	}

	private void updatePageControls()
	{
		float nScoreScreening = getScreeningScore();

		if (form.getLocalContext().getSecondPage().equals(Boolean.FALSE))
		{
			// first page
			form.lblTotalScreening().setVisible(false);
			form.grdAssessment().setVisible(false);
			form.grdScreening().setVisible(true);
			form.btnPrev().setVisible(false);
			form.btnNext().setVisible(true);
			form.btnSave().setVisible(false);
		}
		else
		{
			// second page
			form.lblTotalScreening().setVisible(true);
			form.grdAssessment().setVisible(true);

			setGridTextColor(Color.Black);

			if (nScoreScreening <= 11)
				form.grdAssessment().setReadOnly(false);
			else
			{
				// if(isAnythingAnsweredAssessment() == true)
				// form.grdAssessment().setReadOnly(false);
				// else
				{
					uncheckAssessmentAnswers();
					form.grdAssessment().setReadOnly(true);
					setGridTextColor(Color.LightGray);
				}
			}

			form.grdScreening().setVisible(false);
			form.btnPrev().setVisible(true);
			form.btnNext().setVisible(false);
			form.btnSave().setVisible(true);
		}
	}

	private void uncheckAssessmentAnswers()
	{
		for (int i = 0; i < form.grdAssessment().getRows().size(); i++)
		{
			grdAssessmentRow parent = form.grdAssessment().getRows().get(i);

			for (int j = 0; j < parent.getRows().size(); j++)
			{
				grdAssessmentRow child = parent.getRows().get(j);

				child.setSelect(false);
			}
		}

	}

	protected void onBtnSaveClick() throws ims.framework.exceptions.PresentationLogicException
	{
		if (bCheckData() == false)
			return;

		boolean bIsScreeningAnswered = isEverythingAnsweredScreening();
		boolean bIsAssessmentAnswered = isEverythingAnsweredAssessment();

		if (bIsScreeningAnswered == false)
		{
			engine.showMessage("Please answer all Screening questions !");
			return;
		}

		float nScoreScreening = getScreeningScore();

		if (nScoreScreening <= 11 && bIsAssessmentAnswered == false)
		{
			engine.showMessage("Please answer all Assessment questions !");
			return;
		}

		MiniNutritionalAssessment record = form.getGlobalContext().COE.getMNARecord();

		if (record == null)
		{
			// new
			record = populateDataFromScreen();
		}
		else
		{
			// update
			record = populateDataFromScreen(record);
		}

		if (record == null)
			return;

		record.setAssessmentDetails(new MiniNutritionalAssessmentDetailsCollection());

		// screening
		for (int k = 0; k < form.grdScreening().getRows().size(); k++)
		{
			for (int i = 0; i < form.grdScreening().getRows().get(k).getRows().size(); i++)
			{
				// GenForm.grdScreeningRow row =
				// form.grdScreening().getRows().get(k).getRows().get(i);
				GenForm.grdScreeningRow child = form.grdScreening().getRows().get(k).getRows().get(i);

				// for (int j = 0; j < row.getRows().size(); j++)
				{
					// GenForm.grdScreeningRow child = row.getRows().get(j);

					MiniNutritionalAssessmentDetails detail = new ims.nursing.vo.MiniNutritionalAssessmentDetails();
					detail.setAssessment(new Integer(child.getValue()));
					detail.setSelect(new Boolean(child.getSelect()));

					record.getAssessmentDetails().add(detail);
				}
			}
		}

		// Assessment
		for (int k = 0; k < form.grdAssessment().getRows().size(); k++)
		{
			for (int i = 0; i < form.grdAssessment().getRows().get(k).getRows().size(); i++)
			{
				// GenForm.grdAssessmentRow row =
				// form.grdAssessment().getRows().get(k).getRows().get(i);
				GenForm.grdAssessmentRow child = form.grdAssessment().getRows().get(k).getRows().get(i);

				// for (int j = 0; j < row.getRows().size(); j++)
				{
					// GenForm.grdAssessmentRow child = row.getRows().get(j);

					MiniNutritionalAssessmentDetails detail = new ims.nursing.vo.MiniNutritionalAssessmentDetails();
					detail.setAssessment(new Integer(child.getValue()));
					detail.setSelect(new Boolean(child.getSelect()));

					record.getAssessmentDetails().add(detail);
				}
			}
		}

		if (form.getGlobalContext().Core.getCurrentCareContextIsNotNull())
			record.setCareContext(form.getGlobalContext().Core.getCurrentCareContext());

		String[] errors = record.validate();
		if (errors != null)
		{
			engine.showErrors(errors);
			return;
		}

		MnaEnhancedVo mnaEnhancedRecord = new MnaEnhancedVo();

		mnaEnhancedRecord.setMnaRecord(record);

		VitalSignsVo voVitalSign = new VitalSignsVo();
		VSTypeCollection recordedSigns = new VSTypeCollection();

		if (form.getGlobalContext().COE.getMNARecord() == null)
		{
			// add mode
			VSMetrics voMetrics = new VSMetrics();
			voMetrics.setHeightValue(form.decHeight().getValue());
			voMetrics.setWeightValue(form.decWeight().getValue());
			voMetrics.setBMI(bodyMassIndex(form.decHeight().getValue().floatValue(), form.decWeight().getValue().floatValue()));
			voMetrics.setSurfaceArea(bodySurfaceArea(form.decHeight().getValue().floatValue(), form.decWeight().getValue().floatValue()));
			voMetrics.setHeightEstimatedMeasured(Boolean.TRUE); // default to
			// measured
			voMetrics.setWeightEstimatedMeasured(Boolean.TRUE); // default to
			voMetrics.setPatient(form.getGlobalContext().Core.getPatientShort());

			// measured
			voVitalSign.setMetrics(voMetrics);
			recordedSigns.add(VSType.METRICS);
			voVitalSign.setRecordedSigns(recordedSigns);

			// recording datetime
			Date date = form.dteDate().getValue();
			Time time = form.timTime().getValue();

			DateTime dt = null;
			if (date != null && time != null)
				dt = new DateTime(date, time);

			voVitalSign.setVitalsTakenDateTime(dt);

			AuthoringInformationVo voAuthoring = new AuthoringInformationVo();
			voAuthoring.setAuthoringDateTime(dt);
			voAuthoring.setAuthoringHcp((HcpLiteVo) domain.getHcpLiteUser());
			voVitalSign.setAuthoringInformation(voAuthoring);
			// TODO: commented out this code as attributes no longer valid
			// MemberOfStaffShortVo memStaffShortVo = (MemberOfStaffShortVo) domain.getMosUser();
			// if (memStaffShortVo != null && memStaffShortVo.getHcp() != null)
			// voVitalSign.setAuthoringCP(memStaffShortVo.getHcp());

			if (form.getGlobalContext().Core.getCurrentCareContextIsNotNull())
				voVitalSign.setCareContext(form.getGlobalContext().Core.getCurrentCareContext());

			errors = voVitalSign.validate();
			if (errors != null)
			{
				engine.showErrors(errors);
				return;
			}

			mnaEnhancedRecord.setVsRecord(voVitalSign);
			record.setMetrics(voMetrics);
		}

		errors = mnaEnhancedRecord.validate();
		if (errors != null)
		{
			engine.showErrors(errors);
			return;
		}

		try
		{
			// domain.saveRecord(record,
			// form.getGlobalContext().Core.getClinicalEpisode());

			// If there is an assesment component in the global context, we want
			// to save that too!
			if (form.getGlobalContext().Nursing.getAssessmentComponent() != null && form.getGlobalContext().Nursing.getAssessmentComponent() instanceof AssessmentEatingAndDrinking)
			{
				AssessmentEatingAndDrinking comp = (AssessmentEatingAndDrinking) form.getGlobalContext().Nursing.getAssessmentComponent();
				comp.setMiniNutritionalAssessment(record);

				String[] arrErrors = comp.validate();
				if (arrErrors != null)
				{
					engine.showErrors("Validation Errors", arrErrors);
					return;
				}
				// AssessmentHeaderInfo headerInfo =
				// domain.saveEatingAssessmentComponent(form.getGlobalContext().Nursing.getAssessmentHeaderInfo(),
				// comp, form.getGlobalContext().Core.getClinicalEpisode());
				// Go back to the mobility form
				// form.getGlobalContext().Nursing.setAssessmentHeaderInfo(headerInfo);

				mnaEnhancedRecord.setAedRecord(comp);
				mnaEnhancedRecord.setAshRecord(form.getGlobalContext().Nursing.getAssessmentHeaderInfo());

				errors = mnaEnhancedRecord.validate();
				if (errors != null)
				{
					engine.showErrors(errors);
					return;
				}
			}

			// if(form.getGlobalContext().COE.getMNARecord() == null)
			// domain.insertMetricsRecord(voVitalSign,
			// form.getGlobalContext().Core.getClinicalEpisode());

			MnaEnhancedVo retVO = new MnaEnhancedVo();
			try
			{
				retVO = domain.saveAll(mnaEnhancedRecord, form.getGlobalContext().Core.getCurrentCareContext());
			}
			catch (UniqueKeyViolationException e)
			{
				e.printStackTrace();
			}

			// Go back to the mobility form
			if (retVO != null)
				form.getGlobalContext().Nursing.setAssessmentHeaderInfo(retVO.getAshRecord());

		}
		catch (StaleObjectException e)
		{
			engine.showMessage(ims.configuration.gen.ConfigFlag.UI.STALE_OBJECT_MESSAGE.getValue());
			if (form.getGlobalContext().COE.getMNARecordIsNotNull() &&  form.getGlobalContext().COE.getMNARecord().getID_AssessmentIsNotNull())
				form.getGlobalContext().COE.setMNARecord(domain.getRecord(form.getGlobalContext().COE.getMNARecord().getID_Assessment()));

			onFormOpen();
			return;
			/*form.getGlobalContext().Core.setYesNoDialogMessage(ims.configuration.gen.ConfigFlag.UI.STALE_OBJECT_MESSAGE.getValue());
			engine.open(form.getForms().Core.OkDialog, "Data Warning");
			return;*/
		}
		catch (DomainInterfaceException e)
		{
			engine.showMessage("Error saving MNA assessment record: " + e.getMessage());
			return;
		}

		form.getGlobalContext().COE.setAssessmentScore(getScreeningScore());
		
		if (form.getGlobalContext().COE.getDisplayScoreIsNotNull() && form.getGlobalContext().COE.getDisplayScore().equals(Boolean.TRUE))
		{
			float fScore = getAssessmentScore() + getScreeningScore();
			form.getGlobalContext().COE.setAssessmentScore(new Float(fScore));
		}
		
		engine.close(DialogResult.OK);
	}

	protected void onBtnCancelClick() throws ims.framework.exceptions.PresentationLogicException
	{
		engine.close(DialogResult.CANCEL);
	}

	protected void clearScreen()
	{
		super.clearScreen();
	}

	protected MiniNutritionalAssessment populateDataFromScreen()
	{
		MiniNutritionalAssessment record = super.populateDataFromScreen();

		Object hcpLite = domain.getHcpLiteUser();
		record.setHcpInitiated(hcpLite != null ? ((HcpLiteVo) hcpLite) : null);

		record.setDateTimeInitiated(new DateTime(form.dteDate().getValue(), form.timTime().getValue()));

		return record;
	}

	protected MiniNutritionalAssessment populateDataFromScreen(MiniNutritionalAssessment value)
	{
		MiniNutritionalAssessment record = super.populateDataFromScreen(value);

		record.setDateTimeInitiated(new DateTime(form.dteDate().getValue(), form.timTime().getValue()));

		return record;
	}

	protected void populateScreenFromData(MiniNutritionalAssessment value)
	{
		super.populateScreenFromData(value);
	}

	private boolean bCheckData()
	{
		if (bCheckScreening() == false)
			return false;
		if (bCheckAssessment() == false)
			return false;

		if (form.decWeight().getValue() == null)
		{
			engine.showMessage("Please enter the Weight !");
			return false;
		}

		if (form.decHeight().getValue() == null)
		{
			engine.showMessage("Please enter the Height !");
			return false;
		}

		return true;
	}

	private boolean bCheckAssessment()
	{
		for (int k = 0; k < form.grdAssessment().getRows().size(); k++)
		{
			GenForm.grdAssessmentRow row = form.grdAssessment().getRows().get(k);
			// for (int i = 0; i <
			// form.grdScreening().getRows().get(k).getRows().size(); i++)
			{
				// GenForm.grdScreeningRow row =
				// form.grdScreening().getRows().get(k).getRows().get(i);

				if (row.getValue().equalsIgnoreCase("N"))
				{
					int nFound = 0;
					for (int j = 0; j < row.getRows().size(); j++)
					{
						GenForm.grdAssessmentRow child = row.getRows().get(j);

						if (child.getSelect() == true)
							nFound++;
					}

					if (nFound > 1)
					{
						engine.showMessage("The answers for risk factor '" + row.getRisk() + "' are mutually exclusive. Please select only one answer.");
						return false;
					}
				}
			}
		}

		return true;
	}

	private boolean bCheckScreening()
	{
		for (int k = 0; k < form.grdScreening().getRows().size(); k++)
		{
			GenForm.grdScreeningRow row = form.grdScreening().getRows().get(k);
			// for (int i = 0; i <
			// form.grdScreening().getRows().get(k).getRows().size(); i++)
			{
				// GenForm.grdScreeningRow row =
				// form.grdScreening().getRows().get(k).getRows().get(i);

				if (row.getValue().equalsIgnoreCase("N"))
				{
					int nFound = 0;
					for (int j = 0; j < row.getRows().size(); j++)
					{
						GenForm.grdScreeningRow child = row.getRows().get(j);

						if (child.getSelect() == true)
							nFound++;
					}

					if (nFound > 1)
					{
						engine.showMessage("The answers for risk factor '" + row.getRisk() + "' are mutual exclusive. Please select only one answer.");
						return false;
					}
				}
			}
		}

		return true;
	}

	private float getScreeningScore()
	{
		float nScore = 0;

		RiskAssessment risk;
		RiskDescription descr;

		for (int i = 0; i < form.grdScreening().getRows().size(); i++)
		{
			GenForm.grdScreeningRow row = form.grdScreening().getRows().get(i);

			for (int j = 0; j < row.getRows().size(); j++)
			{
				GenForm.grdScreeningRow child = row.getRows().get(j);

				for (int k = 0; k < form.getGlobalContext().COE.getMNAAssessments().size(); k++)
				{
					risk = form.getGlobalContext().COE.getMNAAssessments().get(k);

					for (int m = 0; m < risk.getRiskFactors().size(); m++)
					{
						descr = risk.getRiskFactors().get(m);

						if (child.getValue().toString().equals(descr.getId()) && child.getSelect() == true)
						{
							nScore += Float.valueOf(descr.getScore()).floatValue();
						}
					}
				}
			}
		}

		return nScore;
	}

	private float getAssessmentScore()
	{
		float nScore = 0;

		RiskAssessment risk = null;
		RiskAssessment lastRisk = null;
		RiskDescription descr = null;

		float partScore;
		for (int i = 0; i < form.grdAssessment().getRows().size(); i++)
		{
			GenForm.grdAssessmentRow row = form.grdAssessment().getRows().get(i);

			risk = null;
			partScore = 0;

			for (int j = 0; j < row.getRows().size(); j++)
			{
				GenForm.grdAssessmentRow child = row.getRows().get(j);

				for (int k = 0; k < form.getGlobalContext().COE.getMNAAssessments().size(); k++)
				{
					risk = form.getGlobalContext().COE.getMNAAssessments().get(k);

					if (risk.getName().charAt(0) >= 'G')
					{
						for (int m = 0; m < risk.getRiskFactors().size(); m++)
						{
							descr = risk.getRiskFactors().get(m);

							if (child.getValue().toString().equals(descr.getId()) && child.getSelect() == true)
							{
								partScore += Float.valueOf(descr.getScore()).floatValue();
								lastRisk = (RiskAssessment) risk.clone();
							}
						}
					}
				}
			}

			if (lastRisk != null && lastRisk.getName().length() > 0 && lastRisk.getName().charAt(0) == 'K')
			{
				if (partScore <= 1)
					partScore = 0;
				else if (partScore == 2)
					partScore = (float) 0.5;
				else if (partScore == 3)
					partScore = 1;
			}

			nScore += partScore;

		}

		return nScore;
	}

	private boolean isEverythingAnsweredScreening()
	{
		for (int i = 0; i < form.grdScreening().getRows().size(); i++)
		{
			GenForm.grdScreeningRow row = form.grdScreening().getRows().get(i);

			boolean bAnswered = false;

			for (int j = 0; j < row.getRows().size(); j++)
			{
				GenForm.grdScreeningRow child = row.getRows().get(j);

				if (child.getSelect() == true)
					bAnswered = true;
			}

			if (bAnswered == false)
				return false;
		}

		return true;
	}

	private boolean isEverythingAnsweredAssessment()
	{
		for (int i = 0; i < form.grdAssessment().getRows().size(); i++)
		{
			GenForm.grdAssessmentRow row = form.grdAssessment().getRows().get(i);

			boolean bAnswered = false;

			for (int j = 0; j < row.getRows().size(); j++)
			{
				GenForm.grdAssessmentRow child = row.getRows().get(j);

				if (child.getSelect() == true)
					bAnswered = true;
			}

			if (bAnswered == false)
				return false;
		}

		return true;
	}

	protected void onDecHeightValueChanged() throws PresentationLogicException
	{
		calculateBMI();
	}

	protected void onDecWeightValueChanged() throws PresentationLogicException
	{
		calculateBMI();
	}

	protected void onGrdScreeningGridCheckBoxClicked(int column, grdScreeningRow row, boolean isChecked) throws PresentationLogicException
	{
		float nScoreScreening = getScreeningScore();
		boolean bIsScreeningAnswered = isEverythingAnsweredScreening();

		form.lblTotalScreening().setValue("Screening score: " + String.valueOf(nScoreScreening));
		form.grdAssessment().setReadOnly(nScoreScreening > 11);

		if (bIsScreeningAnswered == false)
			form.grdAssessment().setReadOnly(true);
	}

	private void calculateBMI()
	{
		if (form.decWeight().getValue() == null)
		{
			return;
		}

		if (form.decHeight().getValue() == null)
		{
			return;
		}

		Float bmi = bodyMassIndex(form.decHeight().getValue().floatValue(), form.decWeight().getValue().floatValue());

		if (bmi == null)
			return;

		for (int i = 0; i < form.grdScreening().getRows().size(); i++)
		{
			GenForm.grdScreeningRow row = form.grdScreening().getRows().get(i);

			boolean bFound = false;
			for (int j = 0; j < row.getRows().size(); j++)
			{
				GenForm.grdScreeningRow child = row.getRows().get(j);

				if (child.getValue().equals("16"))
				{
					child.setSelect(false);

					if (bmi.floatValue() < 19)
					{
						child.setSelect(true);
						bFound = true;
					}
				}
				if (child.getValue().equals("17"))
				{
					child.setSelect(false);

					if (bmi.floatValue() >= 19 && bmi.floatValue() < 21)
					{
						child.setSelect(true);
						bFound = true;
					}
				}
				if (child.getValue().equals("18"))
				{
					child.setSelect(false);

					if (bmi.floatValue() >= 21 && bmi.floatValue() < 23)
					{
						child.setSelect(true);
						bFound = true;
					}
				}
				if (child.getValue().equals("19"))
				{
					child.setSelect(false);

					if (bmi.floatValue() >= 23)
					{
						child.setSelect(true);
						bFound = true;
					}
				}
			}

			if (bFound == true)
			{
				for (int j = 0; j < row.getRows().size(); j++)
				{
					GenForm.grdScreeningRow child = row.getRows().get(j);
					child.setReadOnly(true);
				}
			}
		}

		float nScoreScreening = getScreeningScore();
		boolean bIsScreeningAnswered = isEverythingAnsweredScreening();

		form.lblTotalScreening().setValue("Screening score: " + String.valueOf(nScoreScreening));
		form.grdAssessment().setReadOnly(nScoreScreening > 11);

		if (bIsScreeningAnswered == false)
			form.grdAssessment().setReadOnly(true);
	}

	private void disableBMITree()
	{
		if (form.decWeight().getValue() == null)
		{
			return;
		}

		if (form.decHeight().getValue() == null)
		{
			return;
		}

		for (int i = 0; i < form.grdScreening().getRows().size(); i++)
		{
			GenForm.grdScreeningRow row = form.grdScreening().getRows().get(i);

			boolean bFound = false;
			for (int j = 0; j < row.getRows().size(); j++)
			{
				GenForm.grdScreeningRow child = row.getRows().get(j);

				if (child.getValue().equals("16") && child.getSelect())
				{
					bFound = true;
					break;
				}
				if (child.getValue().equals("17") && child.getSelect())
				{
					bFound = true;
					break;
				}
				if (child.getValue().equals("18") && child.getSelect())
				{
					bFound = true;
					break;
				}
				if (child.getValue().equals("19") && child.getSelect())
				{
					bFound = true;
					break;
				}
			}

			if (bFound == true)
			{
				for (int j = 0; j < row.getRows().size(); j++)
				{
					GenForm.grdScreeningRow child = row.getRows().get(j);
					child.setReadOnly(true);
				}

				break;
			}
		}
	}

	private Float bodyMassIndex(float height/* cm */, float weight/* kg */)
	{
		// we have to convert the HEIGHT from cm to m as the formula requires m
		return new Float((float) (weight / (height / 100.0 * height / 100.0)));
	}

	private Float bodySurfaceArea(float height/* cm */, float weight/* kg */)
	{
		// we have to convert the HEIGHT from cm to m as the formula requires m
		return new Float((float) (0.20247 * Math.pow(height / 100.0, 0.725) * Math.pow(weight, 0.425)));
	}

	protected void onBtnNextClick() throws PresentationLogicException
	{
		boolean bIsScreeningAnswered = isEverythingAnsweredScreening();

		if (bIsScreeningAnswered == false)
		{
			engine.showMessage("Please answer all Screening questions !");
			return;
		}

		if (form.decWeight().getValue() == null && form.getGlobalContext().COE.getMNARecord() == null)
		{
			engine.showMessage("Please enter the Weight !");
			return;
		}

		if (form.decHeight().getValue() == null && form.getGlobalContext().COE.getMNARecord() == null)
		{
			engine.showMessage("Please enter the Height !");
			return;
		}

		if (bCheckScreening() == false)
			return;

		form.getLocalContext().setSecondPage(Boolean.TRUE);
		updatePageControls();
	}

	protected void onBtnPrevClick() throws PresentationLogicException
	{
		form.getLocalContext().setSecondPage(Boolean.FALSE);
		updatePageControls();
	}

	protected void onFormDialogClosed(FormName formName, DialogResult result) throws PresentationLogicException
	{
		if (formName.equals(form.getForms().Core.OkDialog))
		{
			engine.close(DialogResult.OK);
		}
	}

	private void setGridTextColor(Color color)
	{
		for (int i = 0; i < form.grdAssessment().getRows().size(); i++)
		{
			form.grdAssessment().getRows().get(i).setTextColor(color);

			for (int j = 0; j < form.grdAssessment().getRows().get(i).getRows().size(); j++)
				form.grdAssessment().getRows().get(i).getRows().get(j).setTextColor(color);
		}
	}
}
