/FileExtraction/Java_unseen/IMS-MAXIMS_openMAXIMS/Source Library/openmaxims_workspace/Nursing/src/ims/nursing/forms/bradenscaledialog/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 40820.730)
// Copyright (C) 1995-2004 IMS MAXIMS plc. All rights reserved.

package ims.nursing.forms.bradenscaledialog;

import ims.coe.vo.AssessmentSkin;
import ims.coe.vo.RiskAssessment;
import ims.coe.vo.RiskAssessmentCollection;
import ims.coe.vo.RiskDescription;
import ims.core.vo.HcpLiteVo;
import ims.domain.exceptions.DomainInterfaceException;
import ims.domain.exceptions.StaleObjectException;
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.nursing.vo.AssessmentComponent;
import ims.nursing.vo.AssessmentHeaderInfo;
import ims.nursing.vo.BradenScale;
import ims.nursing.vo.BradenScaleDetailsCollection;
import ims.spinalinjuries.vo.NurAssessmentSkinVo;

public class Logic extends BaseLogic
{
	protected void onFormOpen() throws ims.framework.exceptions.FormOpenException
	{
		RiskAssessmentCollection risks = form.getGlobalContext().COE.getBradenAssessments();

		if (risks == null)
		{
			engine.showMessage("Could not retrieve the Braden scale Assessments !");
			return;
		}
		
		form.grdRiskAssessment().setReadOnly(false);
		form.btnEdit().setVisible(false);
		
		BradenScale fall = form.getGlobalContext().COE.getBradenScaleRecord();
		
		if(fall != null && engine.getPreviousNonDialogFormName().equals(form.getForms().COE.AssessSkin))
		{
			form.btnSave().setEnabled(false);
			form.grdRiskAssessment().setReadOnly(true);
			form.btnEdit().setVisible(true);
			form.btnEdit().setEnabled(false);
			if(fall.getAssessmentDetails().size()>0)
				form.btnEdit().setEnabled(true);
		
		}
			

		form.grdRiskAssessment().getRows().clear();
		for (int i = 0; i < risks.size(); i++)
		{
			RiskAssessment risk = risks.get(i);

			GenForm.grdRiskAssessmentRow row = form.grdRiskAssessment().getRows().newRow();

			row.setRisk(risk.getName());
			row.setBold(true);
			row.setBackColor(Color.Beige);
			row.setValue(risk.getMultiple().booleanValue() == true ? "Y" : "N");
			row.setTooltipForRisk(risk.getDescription());

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

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

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

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

			row.setExpanded(true);
		}

		form.lblScore().setValue("Score : " + String.valueOf(getAssessmentScore()));

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

			Object Object = domain.getHcpLiteUser();
			HcpLiteVo hcpLiteVo = Object!=null?(HcpLiteVo)Object:null;
			form.getLocalContext().setHcp(hcpLiteVo);
			

			if (form.getLocalContext().getHcp() != null)
				form.txtHcp().setValue(form.getLocalContext().getHcp().getName().toString());
		}
		else
		{
			form.dteDate().setValue(fall.getDateTimeInitiated().getDate());
			form.timTime().setValue(fall.getDateTimeInitiated().getTime());

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

		// 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 && Boolean.TRUE.equals(comp.getIsComplete()))
		{
			form.btnSave().setEnabled(false);
			form.btnEdit().setVisible(false);
			form.grdRiskAssessment().setReadOnly(true);
		}

		// we can update a Braden record which belongs to an Skin assessment via
		// Skin assessment page only
		if (form.getGlobalContext().COE.getBradenScaleRecordIsNotNull() && comp == null)
		{
			Boolean bIsPart = null;

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

			if (bIsPart == Boolean.TRUE)
			{
				form.btnSave().setEnabled(false);
				form.grdRiskAssessment().setReadOnly(true);
			}
		}
		if( form.getGlobalContext().Core.getAssessmentIsReadOnly() != null && form.getGlobalContext().Core.getAssessmentIsReadOnly() == true )
		{
			form.btnSave().setEnabled(false);
			form.btnCancel().setEnabled(true);
			form.btnEdit().setVisible(false);
			form.grdRiskAssessment().setReadOnly(true);
		}
		

	}

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

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

		BradenScale record = populateDataFromScreen(form.getGlobalContext().COE.getBradenScaleRecord());
		
		String[] errors = record.validate();
		if (errors != null)
		{
			engine.showErrors(errors);
			return;
		}

		try
		{
			// 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 AssessmentSkin
					|| form.getGlobalContext().Nursing.getAssessmentComponent() instanceof NurAssessmentSkinVo))
			{
				AssessmentSkin comp = null;
				NurAssessmentSkinVo nurComp = null;
				AssessmentHeaderInfo headerInfo = null;
				
				if (form.getGlobalContext().Nursing.getAssessmentComponent() instanceof AssessmentSkin)
				{
					comp = (AssessmentSkin) form.getGlobalContext().Nursing.getAssessmentComponent();
					comp.setBradenScale(record);

					String[] arrErrors = comp.validate();
					if (arrErrors != null)
					{
						engine.showErrors("Validation Errors", arrErrors);
						return;
					}
					headerInfo = domain.saveRecord(record, form.getGlobalContext().Nursing.getAssessmentHeaderInfo(), comp);
					
					if(engine.getPreviousNonDialogFormName().equals(form.getForms().COE.AssessSkin))
					{
						
						form.btnEdit().setEnabled(true);
					
					}
				
				
				}
				else if (form.getGlobalContext().Nursing.getAssessmentComponent() instanceof NurAssessmentSkinVo)
				{
					nurComp = (NurAssessmentSkinVo) form.getGlobalContext().Nursing.getAssessmentComponent();
					nurComp.setBradenScale(record);

					String[] arrErrors = nurComp.validate();
					if (arrErrors != null)
					{
						engine.showErrors("Validation Errors", arrErrors);
						return;
					}
					headerInfo = domain.saveRecord(record, form.getGlobalContext().Nursing.getAssessmentHeaderInfo(), nurComp);
					
					//get the BRADEN SCALE record that has just been saved to the DB, so it contains an ID, stick it in the GLOBAL context
					//this will avoid the duplicate record being created in wdev-9142
					BradenScale voBraden = null;
					if(headerInfo.getCurrentComponent() != null && headerInfo.getCurrentComponent() instanceof AssessmentSkin)
						voBraden = ((AssessmentSkin)headerInfo.getCurrentComponent()).getBradenScale();

					if(headerInfo.getCurrentComponent() != null && headerInfo.getCurrentComponent() instanceof NurAssessmentSkinVo)
						voBraden = ((NurAssessmentSkinVo)headerInfo.getCurrentComponent()).getBradenScale();
					
					form.getGlobalContext().COE.setBradenScaleRecord(voBraden);
				}
				
				// Go back to the mobility form
				form.getGlobalContext().Nursing.setAssessmentHeaderInfo(headerInfo);
			}
			else
			{
				domain.saveRecord(record, null, null);
			}

		}
		catch (StaleObjectException e)
		{
			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) {
			form.getGlobalContext().Core.setYesNoDialogMessage(e.getMessage());
			engine.open(form.getForms().Core.OkDialog, "Data Warning");
			return;
		}

		if (form.getGlobalContext().COE.getDisplayScoreIsNotNull() && form.getGlobalContext().COE.getDisplayScore().equals(Boolean.TRUE))
		{
			float fScore = getAssessmentScore();
			form.getGlobalContext().COE.setAssessmentScore(new Float(fScore));
		}

		engine.close(DialogResult.OK);
	}

	private boolean bCheckData()
	{
		for (int i = 0; i < form.grdRiskAssessment().getRows().size(); i++)
		{
			GenForm.grdRiskAssessmentRow row = form.grdRiskAssessment().getRows().get(i);

			// all questions must be answered
			int nAnswers = 0;
			for (int j = 0; j < row.getRows().size(); j++)
			{
				GenForm.grdRiskAssessmentRow child = row.getRows().get(j);

				if (child.getSelect() == true)
				{
					nAnswers++;
					break;
				}
			}
			if (nAnswers == 0)
			{
				engine.showMessage("The question '" + row.getRisk() + "' was not answered !");
				return false;
			}

			if (row.getValue().equalsIgnoreCase("N"))
			{
				int nFound = 0;
				for (int j = 0; j < row.getRows().size(); j++)
				{
					GenForm.grdRiskAssessmentRow 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;
	}

	protected BradenScale populateDataFromScreen(BradenScale value)
	{
		if(value == null)
		{
			value = new BradenScale();
			if (form.getLocalContext().getHcp() != null)
				value.setHcpInitiated(form.getLocalContext().getHcp());
		}
	
		value.setDateTimeInitiated(new DateTime(form.dteDate().getValue(), form.timTime().getValue()));

		value.setAssessmentDetails(new BradenScaleDetailsCollection());

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

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

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

				value.getAssessmentDetails().add(detail);
			}
		}
	
		if (value.getClinicalContact() == null)
			value.setClinicalContact(form.getGlobalContext().Core.getCurrentClinicalContact());
		
		if (value.getCareContext() == null)
			value.setCareContext(form.getGlobalContext().Core.getCurrentCareContext());

		form.getGlobalContext().COE.setBradenScaleRecord(value);

		return value;
	}

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

	private int getAssessmentScore()
	{
		int nScore = 0;

		RiskAssessment risk = null;
		RiskDescription descr = null;

		int partScore;
		for (int i = 0; i < form.grdRiskAssessment().getRows().size(); i++)
		{
			GenForm.grdRiskAssessmentRow row = form.grdRiskAssessment().getRows().get(i);

			risk = null;
			partScore = 0;

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

				for (int k = 0; k < form.getGlobalContext().COE.getBradenAssessments().size(); k++)
				{
					risk = form.getGlobalContext().COE.getBradenAssessments().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)
						{
							partScore += Integer.valueOf(descr.getScore()).intValue();
						}
					}
				}
			}

			nScore += partScore;
		}

		return nScore;
	}

	@Override
	protected void onbtnEditClick() throws PresentationLogicException
	{
		form.btnEdit().setEnabled(false);
		form.btnSave().setEnabled(true);
		form.grdRiskAssessment().setReadOnly(false);
	}
}
