/FileExtraction/Java_unseen/IMS-MAXIMS_openMAXIMS/Source Library/openmaxims_workspace/Nursing/src/ims/nursing/forms/patientmovement/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 Daniel Laffan using IMS Development Environment (version 1.19 build 40709.915)
// Copyright (C) 1995-2004 IMS MAXIMS plc. All rights reserved.

package ims.nursing.forms.patientmovement;

import com.ims.query.builder.client.QueryBuilderClient;
import com.ims.query.builder.client.SeedValue;
import com.ims.query.builder.client.exceptions.QueryBuilderClientException;

import ims.coe.vo.AssessmentMobility;
import ims.coe.vo.PatientHandling;
import ims.coe.vo.PatientHandlingDetails;
import ims.coe.vo.PatientHandlingDetailsCollection;
import ims.coe.vo.PatientHandlingHeader;
import ims.coe.vo.PatientHandlingHeaderCollection;
import ims.coe.vo.PatientMovement;
import ims.coe.vo.PatientMovementDetails;
import ims.coe.vo.PatientMovementDetailsCollection;
import ims.coe.vo.PatientMovementHeader;
import ims.coe.vo.PatientMovementHeaderCollection;
import ims.coe.vo.lookups.LookupHelper;
import ims.coe.vo.lookups.PatientHandlingAssessmentCollection;
import ims.configuration.gen.ConfigFlag;
import ims.core.vo.HcpLiteVo;
import ims.core.vo.MemberOfStaffShortVo;
import ims.core.vo.lookups.PatIdType;
import ims.domain.exceptions.DomainInterfaceException;
import ims.domain.exceptions.StaleObjectException;
import ims.framework.FormName;
import ims.framework.LayerBridge;
import ims.framework.enumerations.DialogResult;
import ims.framework.enumerations.FormMode;
import ims.framework.exceptions.FormOpenException;
import ims.framework.exceptions.PresentationLogicException;
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;

public class Logic extends BaseLogic
{
	protected void onFormOpen() throws ims.framework.exceptions.FormOpenException
	{
		if (form.getGlobalContext().Core.getCurrentCareContext() == null)
			throw new FormOpenException("Care Context is mandatory for this form.");
		
		form.layerControl1().screening().btnCloseScreening().setVisible(false);
		form.layerControl1().movement().btnCloseMovement().setVisible(false);
		form.getLocalContext().setcheckHandlingMovement(Boolean.TRUE);
	
		if(!listPatientMovement())	
			loadMovmentGridFromLookup();

		if(!listPatientHandling())
			loadHandlingGridFromLookup();
		
		showScreening(true);
	}
	
	private void showScreening(boolean bShowLastRecord) 
	{
		form.layerControl1().showscreening();
		// Check the global context.  If there is an assessment component in it, we
		// want to force a new
		//Check if the variable is of type Assessment Mobility - otherwise crashes
		AssessmentMobility comp = null;
		if(form.getGlobalContext().Nursing.getAssessmentComponent() instanceof AssessmentMobility)
			comp = (AssessmentMobility)form.getGlobalContext().Nursing.getAssessmentComponent(); 
		if (comp != null && comp.getPatientHandling() != null)
		{
			// Display the associated record
			form.layerControl1().screening().comboAllScreening().setValue(comp.getPatientHandling());
			form.layerControl1().screening().comboAllScreening().setEnabled(false);
			
			displayHandlingRecord(comp.getPatientHandling());
			
			form.getLocalContext().setLastHandlingRecord(comp.getPatientHandling());
			form.getLocalContext().setComponentComplete(comp.getIsComplete());
		}
		else if(comp != null)
		{
			form.layerControl1().screening().btnNewScreening().setEnabled(true);
			form.layerControl1().screening().btnUpdateScreening().setEnabled(false);
			
			loadHandlingGridFromLookup();
		}
		else
		{	
			if(bShowLastRecord){
				//show last record - am presuming list will return in correct datetime order
				if(form.getLocalContext().getLastHandlingRecord() != null)
				{		
					form.layerControl1().screening().comboAllScreening().setValue(form.getLocalContext().getLastHandlingRecord()); // id of latest record
					displayHandlingRecord(form.getLocalContext().getLastHandlingRecord());
					form.layerControl1().screening().btnNewScreening().setEnabled(true);
					form.layerControl1().screening().btnUpdateScreening().setEnabled(false);
				}
				else
				{
					form.layerControl1().screening().btnNewScreening().setEnabled(true);
				}
			}
			else{
				if(form.getLocalContext().getPatientHandlingItem() != null)
				{		
					form.layerControl1().screening().comboAllScreening().setValue(form.getLocalContext().getPatientHandlingItem());
					displayHandlingRecord(form.getLocalContext().getPatientHandlingItem());
					form.layerControl1().screening().btnNewScreening().setEnabled(true);
					form.layerControl1().screening().btnUpdateScreening().setEnabled(false);
				}
				else
				{
					form.layerControl1().screening().btnNewScreening().setEnabled(true);
				}
			}
		}
		
		// If there is an associated mobility component for this assessment that is complete
		// we want to disable the save button
		AssessmentComponent acomp = form.getGlobalContext().Nursing.getAssessmentComponent();
		if (acomp != null && acomp.getIsComplete().booleanValue() == true)
		{
			form.getLocalContext().setComponentComplete(Boolean.TRUE);
			form.layerControl1().screening().btnNewScreening().setEnabled(false);
			form.layerControl1().screening().btnUpdateScreening().setEnabled(false);
			form.layerControl1().screening().btnCancelScreening().setVisible(false);
			form.layerControl1().screening().btnCloseScreening().setVisible(true);
			form.layerControl1().movement().btnCancelMovement().setVisible(false);
			form.layerControl1().movement().btnCloseMovement().setVisible(true);
		}
		
		checkHandlingPartOfAssessment();
	}

	protected void onBtnNewScreeningClick() throws ims.framework.exceptions.PresentationLogicException
	{
		form.layerControl1().screening().comboAllScreening().setValue(null);
		makeHandlingHeaderInfoNew(Boolean.TRUE);
		loadHandlingGridFromLookup();
		
		PatientHandling handling = new PatientHandling();
		form.getLocalContext().setPatientHandlingItem(handling);
		
		form.setMode(FormMode.EDIT);
		form.layerControl1().movement().setHeaderEnabled(false);
	}
	
	
	protected void onBtnUpdateScreeningClick() throws ims.framework.exceptions.PresentationLogicException
	{
		form.setMode(FormMode.EDIT);
		form.layerControl1().movement().setHeaderEnabled(false);
	}
	
	protected void onBtnSaveScreeningClick() throws ims.framework.exceptions.PresentationLogicException
	{
		if(!fillHandlingRecord())
			return;
			
		PatientHandling handling = form.getLocalContext().getPatientHandlingItem();
		
		if(handling == null)
			return;
		
		if (handling.getClinicalContact() == null)
			handling.setClinicalContact(form.getGlobalContext().Core.getCurrentClinicalContact());
		
		if (handling.getCareContext() == null)
			handling.setCareContext(form.getGlobalContext().Core.getCurrentCareContext());
			
		String[] arrErrors = handling.validate();
		if(arrErrors == null)
		{
			try 
			{
				
				// If there is an assesment component in the global context, we want to save that too!
				if (form.getGlobalContext().Nursing.getAssessmentComponent() != null)
				{
					AssessmentHeaderInfo headerInfo = domain.savePatientHandling(handling, form.getGlobalContext().Nursing.getAssessmentHeaderInfo(), form.getGlobalContext().Nursing.getAssessmentComponent());
					form.getGlobalContext().Nursing.setAssessmentHeaderInfo(headerInfo);
				 	//WDEV-3828
					form.getGlobalContext().Nursing.setAssessmentComponent(headerInfo != null ?  headerInfo.getCurrentComponent() : null);
				}
				else
					form.getLocalContext().setPatientHandlingItem(domain.savePatientHandlingNoAssessment(handling));
			}
			catch (StaleObjectException e) 
			{
				if(form.layerControl1().screening().comboAllScreening().getValue() != null)
				{
					engine.showMessage(ims.configuration.gen.ConfigFlag.UI.STALE_OBJECT_MESSAGE.getValue());
					displayHandlingRecord(form.layerControl1().screening().comboAllScreening().getValue());
					form.setMode(FormMode.VIEW);
					form.layerControl1().screening().btnNewScreening().setEnabled(true);
					return;
				}
			}
		}
		else
		{
			engine.showErrors("Validation Errors", arrErrors);
			return;
		}	
		
		listPatientHandling();
		showScreening(false);
		form.setMode(FormMode.VIEW);
		form.layerControl1().movement().setHeaderEnabled(true);
	}
	
	protected void onBtnCancelScreeningClick() throws ims.framework.exceptions.PresentationLogicException
	{
		if (form.getGlobalContext().Nursing.getAssessmentComponent() != null)
		{
			engine.open(form.getForms().COE.AssessMobility);
			return;
		}
		
		loadHandlingGridFromLookup();
		makeHandlingHeaderInfoNew(Boolean.FALSE);
		if(form.getLocalContext().getPatientHandlingItem().getID_AssessmentIsNotNull())
			showScreening(false);
		else
			showScreening(true);
		form.setMode(FormMode.VIEW);	
		form.layerControl1().movement().setHeaderEnabled(true);
	}
	
	protected void onComboAllScreeningValueChanged() throws PresentationLogicException 
	{
		if(form.layerControl1().screening().comboAllScreening().getValue() != null)
		{	
			displayHandlingRecord(form.layerControl1().screening().comboAllScreening().getValue());
			form.layerControl1().screening().btnUpdateScreening().setEnabled(true);
		}
		else
		{
			loadHandlingGridFromLookup();
			makeHandlingHeaderInfoNew(Boolean.FALSE);
			form.layerControl1().screening().btnUpdateScreening().setEnabled(false);
		}	
		checkHandlingPartOfAssessment();	
	}
	
		
	private void showMovement(boolean bShowLastRecord) 
	{
		form.layerControl1().showmovement();
		
		// Check the global context.  If there is an assessment component in it, we
		// want to force a new
		AssessmentMobility comp = (AssessmentMobility)form.getGlobalContext().Nursing.getAssessmentComponent(); 
		if (comp != null && comp.getPatientMovement() != null)
		{
			// Display the associated record
			form.layerControl1().movement().comboAllMovements().setValue(comp.getPatientMovement());
			form.layerControl1().movement().comboAllMovements().setEnabled(false);
			displayMovementRecord(comp.getPatientMovement());
				
			form.getLocalContext().setComponentComplete(comp.getIsComplete());
			form.getLocalContext().setLastMovementRecord(comp.getPatientMovement());
		}
		else if(comp != null)
		{
			form.layerControl1().movement().btnNewMovement().setEnabled(true);
			form.layerControl1().movement().btnUpdateMovement().setEnabled(false);
			
			loadMovmentGridFromLookup();
		}
		else
		{	
			//show last record - am presuming list will return in correct datetime order
			if(bShowLastRecord){
				if(form.getLocalContext().getLastMovementRecord() != null)
				{	
					form.layerControl1().movement().comboAllMovements().setValue(form.getLocalContext().getLastMovementRecord());
					displayMovementRecord(form.getLocalContext().getLastMovementRecord());
					form.layerControl1().movement().btnNewMovement().setEnabled(true);
					form.layerControl1().movement().btnUpdateMovement().setEnabled(false);
					
				}
				else
					form.layerControl1().movement().btnNewMovement().setEnabled(true);
			}
			else{
				if(form.getLocalContext().getPatientMovementItem() != null)
				{	
					form.layerControl1().movement().comboAllMovements().setValue(form.getLocalContext().getPatientMovementItem());
					displayMovementRecord(form.getLocalContext().getPatientMovementItem());
					form.layerControl1().movement().btnNewMovement().setEnabled(true);
					form.layerControl1().movement().btnUpdateMovement().setEnabled(false);
					
				}
				else
					form.layerControl1().movement().btnNewMovement().setEnabled(true);				
			}
		}
		
		// If there is an associated mobility component for this assessment that is complete
		// we want to disable the save button
		AssessmentComponent acomp = form.getGlobalContext().Nursing.getAssessmentComponent();
		if (acomp != null && acomp.getIsComplete().booleanValue() == true)
		{
			form.getLocalContext().setComponentComplete(Boolean.TRUE);
			form.layerControl1().movement().btnNewMovement().setEnabled(false);
			form.layerControl1().movement().btnUpdateMovement().setEnabled(false);
			form.layerControl1().movement().btnCancelMovement().setVisible(false);
			form.layerControl1().movement().btnCloseMovement().setVisible(true);
		}
		checkMovementPartOfAssessment();
	}

	protected void onBtnNewMovementClick() throws ims.framework.exceptions.PresentationLogicException
	{
		form.layerControl1().movement().comboAllMovements().setValue(null);
		makeMovementHeaderInfoNew(Boolean.TRUE);
		loadMovmentGridFromLookup();
		PatientMovement movement = new PatientMovement();
		form.getLocalContext().setPatientMovementItem(movement);
		form.setMode(FormMode.EDIT);
		form.layerControl1().screening().setHeaderEnabled(false);
	
	}
	
	protected void onBtnUpdateMovementClick() throws ims.framework.exceptions.PresentationLogicException
	{ 
		form.setMode(FormMode.EDIT);
		form.layerControl1().screening().setHeaderEnabled(false);
	}
	
	protected void onBtnSaveMovementClick() throws ims.framework.exceptions.PresentationLogicException
	{
		if(!fillMovementRecord())
			return;
			
		PatientMovement movement = form.getLocalContext().getPatientMovementItem();
		
		if(movement == null)
			return;
	
		if (movement.getClinicalContact() == null)
			movement.setClinicalContact(form.getGlobalContext().Core.getCurrentClinicalContact());
		
		if (movement.getCareContext() == null)
			movement.setCareContext(form.getGlobalContext().Core.getCurrentCareContext());

		String[] arrErrors = movement.validate();
		if(arrErrors == null)
		{
			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 AssessmentMobility)
				//if (form.getGlobalContext().Nursing.getAssessmentComponent() != null)
				{
					AssessmentHeaderInfo headerInfo = domain.savePatientMovement(movement, form.getGlobalContext().Nursing.getAssessmentHeaderInfo(), form.getGlobalContext().Nursing.getAssessmentComponent());
					// Go back to the mobility form
					form.getGlobalContext().Nursing.setAssessmentHeaderInfo(headerInfo);
					form.getGlobalContext().Nursing.setAssessmentComponent(headerInfo.getCurrentComponent());
				}
				else
					form.getLocalContext().setPatientMovementItem(domain.savePatientMovementNoAssessment(movement));
				
			} 
			catch (StaleObjectException e) 
			{
				engine.showMessage(ims.configuration.gen.ConfigFlag.UI.STALE_OBJECT_MESSAGE.getValue());
				displayMovementRecord(form.layerControl1().movement().comboAllMovements().getValue());
				form.layerControl1().movement().btnNewMovement().setEnabled(true);
				form.setMode(FormMode.VIEW);
				return;
			}
		}	
		else
		{
			engine.showErrors("Validation Errors", arrErrors);
			return;
		}
		
		listPatientMovement();
		form.setMode(FormMode.VIEW);
		showMovement(false);
		form.layerControl1().screening().setHeaderEnabled(true);
	}
	protected void onBtnCancelMovementClick() throws ims.framework.exceptions.PresentationLogicException
	{
		if (form.getGlobalContext().Nursing.getAssessmentComponent() != null)
		{
			engine.open(form.getForms().COE.AssessMobility);
			return;
		}

		loadMovmentGridFromLookup();
		makeMovementHeaderInfoNew(Boolean.FALSE);
		if(form.getLocalContext().getPatientMovementItem().getID_AssessmentIsNotNull())
			showMovement(false);
		else
			showMovement(true);
		form.setMode(FormMode.VIEW);
		form.layerControl1().screening().setHeaderEnabled(true);
	}
	
	protected void onGridMovementSelectionChanged() throws ims.framework.exceptions.PresentationLogicException
	{
		PatientMovementDetails value = form.layerControl1().movement().gridMovement().getValue();
		if (value!= null && value.getID_PatientMovementHandlingDetailsIsNotNull())
			form.getGlobalContext().COE.setPatientMovementID(value.getID_PatientMovementHandlingDetails());
	}
	
	protected void onBtnPrintMovementClick() throws ims.framework.exceptions.PresentationLogicException
	{
		engine.open(form.getForms().Core.Reports);
	}
	
	
	protected void onComboAllMovementsValueChanged() throws PresentationLogicException 
	{
		if(form.layerControl1().movement().comboAllMovements().getValue() != null)
		{	
			displayMovementRecord(form.layerControl1().movement().comboAllMovements().getValue());
			form.layerControl1().movement().btnUpdateMovement().setEnabled(true);
		}
		else
		{
			loadMovmentGridFromLookup();
			makeMovementHeaderInfoNew(Boolean.FALSE);
			form.layerControl1().movement().btnUpdateMovement().setEnabled(false);
		}	
		checkMovementPartOfAssessment();
	}
			
	boolean listPatientHandling()
	{
		PatientHandlingHeaderCollection handlingColl = new PatientHandlingHeaderCollection();

		handlingColl = domain.listPatientHandling(form.getGlobalContext().Core.getCurrentCareContext()); //wdev-1571
		
		if(handlingColl != null && handlingColl.size() != 0)
		{
			boolean bFirstRecord = true;

			form.layerControl1().screening().comboAllScreening().clear();
			for (int i=0; i<handlingColl.size(); i++)
			{
				PatientHandlingHeader handling = handlingColl.get(i);
				//Load ComboBox with Records Retrieved
				form.layerControl1().screening().comboAllScreening().newRow(handling,handling.getDateTimeInitiated().toString());
				if(bFirstRecord)
				{	
					form.getLocalContext().setLastHandlingRecord(handling);
					bFirstRecord = false;
				}
			}	
		}	
		else
			return false;
		
		return true;
	}
	
	boolean listPatientMovement()
	{
		PatientMovementHeaderCollection movementColl = new PatientMovementHeaderCollection();
		movementColl = domain.listPatientMovement(form.getGlobalContext().Core.getCurrentCareContext());
		
		if(movementColl!=null && movementColl.size() != 0)
		{
			boolean bFirstRecord = true;
			form.layerControl1().movement().comboAllMovements().clear();
			for (int i=0; i<movementColl.size(); i++)
			{
				PatientMovementHeader movement = movementColl.get(i);
				//Load ComboBox with Records Retrieved
				form.layerControl1().movement().comboAllMovements().newRow(movement,movement.getDateTimeInitiated().toString());
				if(bFirstRecord)
				{	
					form.getLocalContext().setLastMovementRecord(movement);
					bFirstRecord = false;
				}
			}	
		}
		else
			return false;
		
		return true;
	}
	
	void displayHandlingRecord(PatientHandlingHeader handlingHeader)
	{
		if (handlingHeader.getID_Assessment() == null)
			return;
		
		PatientHandling handling = domain.getPatientHandling(handlingHeader);
		
		if(handling != null)
		{
			form.getLocalContext().setPatientHandlingItem(handling); 
			//contine here displaying header info then get the details
			form.layerControl1().screening().dateScreening().setValue(handling.getDateTimeInitiated().getDate());
			form.layerControl1().screening().timeScreening().setValue(handling.getDateTimeInitiated().getTime());
			if (handling.getHcpInitiated() != null && handling.getHcpInitiated().getName() != null)
				form.layerControl1().screening().txtRecordingHcpScreening().setValue(handling.getHcpInitiated().getName().toString());
			
			loadHandlingGridFromLookup();
			
			PatientHandlingDetailsCollection coll = handling.getPatientHandlingDetails();
			for(int i=0;i<coll.size();i++)
			{
				GenForm.layerControl1Layer.screeningContainer.gridScreeningRow row = null;
				int r=0;
				for(r=0;r<form.layerControl1().screening().gridScreening().getRows().size(); r++)
				{	
					row = form.layerControl1().screening().gridScreening().getRows().get(r);
					if(coll.get(i).getAssessment().equals(row.getcolAssessment()))
					{
						row.setValue(coll.get(i));
						row.setcolStatus(coll.get(i).getStatus()); 
						row.setcolDetails(coll.get(i).getDetails());
						break;
					}
				}
				if(r == form.layerControl1().screening().gridScreening().getRows().size())
				{
					row = form.layerControl1().screening().gridScreening().getRows().newRow();
					row.setValue(coll.get(i));
					row.setcolAssessment(coll.get(i).getAssessment());
					row.setcolStatus(coll.get(i).getStatus()); 
					row.setcolDetails(coll.get(i).getDetails());
				}
			}
		}
	}
	
	void loadHandlingGridFromLookup()
	{
		form.layerControl1().screening().gridScreening().getRows().clear();
		PatientHandlingAssessmentCollection coll = LookupHelper.getPatientHandlingAssessment(domain.getLookupService());
		for(int i=0;i<coll.size();i++)
		{
			GenForm.layerControl1Layer.screeningContainer.gridScreeningRow row = form.layerControl1().screening().gridScreening().getRows().newRow();
			row.setcolAssessment(coll.get(i));		
			row.setValue(new PatientHandlingDetails());	
		}
	}
	
	void displayMovementRecord(PatientMovementHeader movementHeader)
	{
		PatientMovement movement = domain.getPatientMovement(movementHeader);
		
		if(movement != null)
		{
			form.getLocalContext().setPatientMovementItem(movement); 
			form.getGlobalContext().COE.setPatientMovementID(movement.getID_Assessment());
			//contine here displaying header info then get the details
			form.layerControl1().movement().dateMovement().setValue(movement.getDateTimeInitiated().getDate());
			form.layerControl1().movement().timeMovement().setValue(movement.getDateTimeInitiated().getTime());
			if (movement.getHcpInitiated() != null)
				form.layerControl1().movement().txtRecordingHcpMOVE().setValue(movement.getHcpInitiated().toString());
			
			loadMovmentGridFromLookup();
			
			PatientMovementDetailsCollection coll = movement.getPatientMovementDetails();
			PatientMovementDetailsCollection collInactive = new PatientMovementDetailsCollection();
			GenForm.layerControl1Layer.movementContainer.gridMovementRow row = null;
			for(int i=0;i<coll.size();i++)
			{
				int r=0;
				for (r=0; r<form.layerControl1().movement().gridMovement().getAllRows().length; r++)
				{
					row = form.layerControl1().movement().gridMovement().getAllRows()[r];
					if(coll.get(i).getMovement().equals(row.getcolMove()))
					{
						row.setValue(coll.get(i));
						row.setcolEquipment(coll.get(i).getMechanicalEquipment());
						row.setColOtherEquipment(coll.get(i).getEquipmentOther());
						if(coll.get(i).getNumberOfStaff() != null)
							row.setcolStaff(coll.get(i).getNumberOfStaff());

						row.setcolDetails(coll.get(i).getDetails());
						break;
					}
				}
				if(r == form.layerControl1().movement().gridMovement().getAllRows().length)
				{
					collInactive.add(coll.get(i));
				}
			}
				
			//inactive record handling
			PatientMovementDetails item = null;
			ims.coe.vo.lookups.PatientMovement itemParent = null;
			for(int i=0;i<collInactive.size();i++)
			{
				item = collInactive.get(i);
				itemParent = item.getMovement().getParent();
				if(itemParent != null)
				{
					GenForm.layerControl1Layer.movementContainer.gridMovementRow rowChild = null;
					int j=0;
					for(j=0;j<form.layerControl1().movement().gridMovement().getRows().size();j++)
					{
						row = form.layerControl1().movement().gridMovement().getRows().get(j);
						if(row.getcolMove().equals(itemParent))
						{
							rowChild = row.getRows().newRow();
							rowChild.setValue(item);
							rowChild.setcolMove(item.getMovement());
							rowChild.setcolEquipment(item.getMechanicalEquipment());
							rowChild.setColOtherEquipment(item.getEquipmentOther());
							if(item.getNumberOfStaff() != null)
								rowChild.setcolStaff(item.getNumberOfStaff());

							rowChild.setcolDetails(item.getDetails());
							break;
						}
					}
					if(j == form.layerControl1().movement().gridMovement().getAllRows().length)
					{
						row = row.getRows().newRow();
						row.setValue(item);
						row.setcolMove(item.getMovement());
						row.setcolEquipment(item.getMechanicalEquipment());
						row.setColOtherEquipment(item.getEquipmentOther());
						if(item.getNumberOfStaff() != null)
						row.setcolStaff(item.getNumberOfStaff());

						row.setcolDetails(item.getDetails());
					}
				}
				else
				{
					row = row.getRows().newRow();
					row.setValue(item);
					row.setcolMove(item.getMovement());
					row.setcolEquipment(item.getMechanicalEquipment());
					row.setColOtherEquipment(item.getEquipmentOther());
					if(item.getNumberOfStaff() != null)
					row.setcolStaff(item.getNumberOfStaff());

					row.setcolDetails(item.getDetails());			
				}
			}	
 			
		}
	}
	
	void loadMovmentGridFromLookup()
	{
		form.layerControl1().movement().gridMovement().populateTree(LookupHelper.getPatientMovement(domain.getLookupService()),true);
		form.layerControl1().movement().gridMovement().expandAll();
	}
	
	boolean fillHandlingRecord()
	{
		PatientHandling handling = form.getLocalContext().getPatientHandlingItem();
		if(handling == null)
			return false;
		
		// WDEV-7770 - Get current date time
		handling.setDateTimeInitiated(new DateTime());
		
		Object hcpLite = domain.getHcpLiteUser();
		handling.setHcpInitiated(hcpLite != null ? ((HcpLiteVo)hcpLite) : null);
		
		//retrieve details from the grid
		PatientHandlingDetailsCollection detailsColl = new PatientHandlingDetailsCollection();
		
		for(int i=0; i<form.layerControl1().screening().gridScreening().getRows().size();i++)
		{
			GenForm.layerControl1Layer.screeningContainer.gridScreeningRow row = form.layerControl1().screening().gridScreening().getRows().get(i);
			
			row.getValue().setAssessment(row.getcolAssessment());
			row.getValue().setDetails(row.getcolDetails());
			row.getValue().setStatus(row.getcolStatus()); 
			
			// if existing record has been cleared
			if(row.getValue().getID_PatientMovementHandlingScreeningDetails() != null)
			{
				if(row.getValue().getStatus() == null && 
						(row.getValue().getDetails() == null || row.getValue().getDetails().equals(""))) 
				{
					engine.showMessage("Previously entered information for a handling cannot be cleared completely");
					return false;
				}
				detailsColl.add(row.getValue());	
			}
			else if(row.getValue().getStatus() != null || (row.getcolDetails() != null && !row.getcolDetails().equals("")))
				detailsColl.add(row.getValue());
		}	
		
		if(detailsColl.size() == 0)
		{
			engine.showMessage("You must save some handling details");
			return false;
		}
		
		handling.setPatientHandlingDetails(detailsColl);
		form.getLocalContext().setPatientHandlingItem(handling);
		
		return true;
	}
	
	boolean fillMovementRecord()
	{
		PatientMovement movement = form.getLocalContext().getPatientMovementItem();
		if(movement == null)
			return false;
		
		// WDEV-7770 - Get current date
		movement.setDateTimeInitiated(new DateTime());
		
		Object hcpLite = domain.getHcpLiteUser();
		movement.setHcpInitiated(hcpLite != null ? ((HcpLiteVo)hcpLite) : null);
		
		//retrieve details from the grid
		PatientMovementDetailsCollection detailsColl = new PatientMovementDetailsCollection();
		
		for(int i=0; i<form.layerControl1().movement().gridMovement().getRows().size();i++)
		{
			for(int r=0; r<form.layerControl1().movement().gridMovement().getRows().get(i).getRows().size(); r++)
			{
				GenForm.layerControl1Layer.movementContainer.gridMovementRow row = form.layerControl1().movement().gridMovement().getRows().get(i).getRows().get(r);
				
				PatientMovementDetails detailsItem = null;
				if (row.getValue() == null)
					detailsItem = new PatientMovementDetails();
				else
					detailsItem = row.getValue();
				
				detailsItem.setMovement(row.getcolMove()); 
				detailsItem.setEquipmentOther(row.getColOtherEquipment());
				detailsItem.setMechanicalEquipment(row.getcolEquipment());
				
				if(row.getcolStaff() != null && !row.getcolStaff().equals(""))
					detailsItem.setNumberOfStaff(row.getcolStaff());
				
				if ( (row.getcolStaff() != null && !row.getcolStaff().equals("")) && (row.getcolStaff().toString().length() > 2) )
				{
					engine.showMessage("The value entered for number of staff is more than two chars. Please enter a realistic number.");
					return false;
				}
				detailsItem.setDetails(row.getcolDetails());
				
				if(row.getValue() != null)
				{
					detailsItem.setID_PatientMovementHandlingDetails(row.getValue().getID_PatientMovementHandlingDetails());
					if(row.getcolEquipment() == null && (row.getcolDetails() == null || row.getcolDetails().equals("")) && row.getColOtherEquipment() == null && (row.getcolStaff() == null || row.getcolStaff().equals(""))) //if existing record has been cleared
					{
						engine.showMessage("Previously entered information for a movement cannot be cleared completely");
						return false;
					}
					detailsColl.add(detailsItem);	
						
				}
				else if(row.getcolEquipment() != null || (row.getcolDetails() != null && !row.getcolDetails().equals("")) || row.getColOtherEquipment() != null || (row.getcolStaff() != null &&!row.getcolStaff().equals("")))
					detailsColl.add(detailsItem);
			}
		}	
		
		if(detailsColl.size() == 0)
		{
			engine.showMessage("You must save some movement details");
			return false;
		}
		
		movement.setPatientMovementDetails(detailsColl);
		form.getLocalContext().setPatientMovementItem(movement);
		
		return true;
	}
	
	void makeHandlingHeaderInfoNew(Boolean bDefaultValues)
	{
		if(bDefaultValues.booleanValue() == true)
		{
			form.layerControl1().screening().dateScreening().setValue(new Date());
			form.layerControl1().screening().timeScreening().setValue(new Time());
			if(domain.getMosUser() != null)
				form.layerControl1().screening().txtRecordingHcpScreening().setValue(((MemberOfStaffShortVo)domain.getMosUser()).toString());
		}
		else //null values
		{
			form.layerControl1().screening().dateScreening().setValue(null);
			form.layerControl1().screening().timeScreening().setValue(null);
			form.layerControl1().screening().txtRecordingHcpScreening().setValue(null);
		}	
	}

	void makeMovementHeaderInfoNew(Boolean bDefaultValues)
	{
		if(bDefaultValues.booleanValue() == true)
		{
			form.layerControl1().movement().dateMovement().setValue(new Date());
			form.layerControl1().movement().timeMovement().setValue(new Time());
			if(domain.getMosUser() != null)
				form.layerControl1().movement().txtRecordingHcpMOVE().setValue(((MemberOfStaffShortVo)domain.getMosUser()).toString());				
		}
		else //null values
		{
			form.layerControl1().movement().dateMovement().setValue(null);
			form.layerControl1().movement().timeMovement().setValue(null);
			form.layerControl1().movement().txtRecordingHcpMOVE().setValue(null);
		}	
	}
	
	protected void onFormModeChanged() 
	{
		if(form.getMode() == FormMode.VIEW)
		{
			form.layerControl1().screening().btnUpdateScreening().setEnabled(true);
			form.layerControl1().screening().comboAllScreening().setEnabled(true);
			form.layerControl1().movement().btnUpdateMovement().setEnabled(true);
			form.layerControl1().movement().comboAllMovements().setEnabled(true);

			form.layerControl1().screening().btnCancelScreening().setVisible(false);
			form.layerControl1().movement().btnCancelMovement().setVisible(false);
			//form.layerControl1().movement().btnNewMovement().setEnabled(true);
			//form.layerControl1().screening().btnNewHandling().setEnabled(true);
			if(form.layerControl1().movement().comboAllMovements().getValues().size() == 0)
			{
				form.layerControl1().movement().btnUpdateMovement().setEnabled(false);
				form.layerControl1().movement().comboAllMovements().setEnabled(false);
			}
			if(form.layerControl1().screening().comboAllScreening().getValues().size() == 0)
			{
				form.layerControl1().screening().btnUpdateScreening().setEnabled(false);
				form.layerControl1().screening().comboAllScreening().setEnabled(false);
			}
			

			
			// In View mode, the cancel button should be enabled when coming from an assessment component
			if (form.getGlobalContext().Nursing.getAssessmentComponent() != null)
			{
				form.layerControl1().screening().btnCloseScreening().setVisible(true);
				form.layerControl1().movement().btnCloseMovement().setVisible(true);
				
				// For Completed component, if complete, cannot update the record
				if (form.getLocalContext().getComponentComplete() != null && form.getLocalContext().getComponentComplete().booleanValue() == true)
				{
					form.layerControl1().movement().btnUpdateMovement().setEnabled(false);
					form.layerControl1().screening().btnUpdateScreening().setEnabled(false);
					form.layerControl1().screening().comboAllScreening().setEnabled(false);
					form.layerControl1().movement().comboAllMovements().setEnabled(false);
				}	
				else
				{ 
					if(form.layerControl1().screening().comboAllScreening().getValues().size() != 0)
					{
						form.layerControl1().screening().btnUpdateScreening().setEnabled(true);
						form.layerControl1().screening().comboAllScreening().setEnabled(false);
						form.layerControl1().screening().btnCloseScreening().setVisible(true);
					}	
					if(form.layerControl1().movement().comboAllMovements().getValues().size() != 0)
					{
						form.layerControl1().movement().btnUpdateMovement().setEnabled(true);
						form.layerControl1().movement().comboAllMovements().setEnabled(false);
						form.layerControl1().movement().btnCloseMovement().setVisible(true);
					}	
				}			
				
				AssessmentMobility comp = null;
				if(form.getGlobalContext().Nursing.getAssessmentComponent() instanceof AssessmentMobility)
					comp = (AssessmentMobility)form.getGlobalContext().Nursing.getAssessmentComponent(); 
				if (comp != null && comp.getPatientHandling() != null)
				{
					form.layerControl1().screening().btnNewScreening().setEnabled(false);
				}
				else if(comp != null)
				{
					form.layerControl1().screening().btnNewScreening().setEnabled(true);
					form.layerControl1().screening().btnUpdateScreening().setEnabled(false);
				}
				else
				{
					if (form.getLocalContext().getLastHandlingRecord() != null)
						form.layerControl1().screening().btnNewScreening().setEnabled(false);
				}
					
				if (comp != null && comp.getPatientMovement() != null)
				{
					form.layerControl1().movement().btnNewMovement().setEnabled(false);
				}
				else if(comp != null)
				{
					form.layerControl1().movement().btnNewMovement().setEnabled(true);
					form.layerControl1().movement().btnUpdateMovement().setEnabled(false);
				}
				else
				{
					if (form.getLocalContext().getLastMovementRecord() != null)
						form.layerControl1().movement().btnNewMovement().setEnabled(false);
				}
			}
		}
		if(form.getMode() == FormMode.EDIT)
		{
			form.layerControl1().screening().btnUpdateScreening().setEnabled(false);
			form.layerControl1().screening().comboAllScreening().setEnabled(false);
			form.layerControl1().movement().btnUpdateMovement().setEnabled(false);
			form.layerControl1().movement().comboAllMovements().setEnabled(false);
			form.layerControl1().screening().btnCancelScreening().setVisible(true);
			form.layerControl1().movement().btnCancelMovement().setVisible(true);
			form.layerControl1().screening().btnCancelScreening().setEnabled(true);
			form.layerControl1().movement().btnCancelMovement().setEnabled(true);
			form.layerControl1().movement().btnNewMovement().setEnabled(false);
			form.layerControl1().screening().btnNewScreening().setEnabled(false);


			
			if (form.getGlobalContext().Nursing.getAssessmentComponent() != null)
			{
				form.layerControl1().screening().btnCloseScreening().setVisible(false);
				form.layerControl1().movement().btnCloseMovement().setVisible(false);
				form.layerControl1().screening().btnCancelScreening().setEnabled(true);
				form.layerControl1().movement().btnCancelMovement().setEnabled(true);
			}
		}
		//After onFormOpen it will run into onFormMode automatically, therefore must call
		//checkHandling the first time from here after everything else
		if(form.getLocalContext().getcheckHandlingMovementIsNotNull())
		{
			if(form.getLocalContext().getcheckHandlingMovement().booleanValue() == true)
			{
				form.getLocalContext().setcheckHandlingMovement(Boolean.FALSE);
				checkHandlingPartOfAssessment();
			}	
		}
	}

	protected void onBtnCloseScreeningClick() throws PresentationLogicException 
	{
		if (form.getGlobalContext().Nursing.getAssessmentComponent() != null)
		{
			engine.open(form.getForms().COE.AssessMobility);
			return;
		}	
	}

	protected void onBtnCloseMovementClick() throws PresentationLogicException 
	{
		if (form.getGlobalContext().Nursing.getAssessmentComponent() != null)
		{
			engine.open(form.getForms().COE.AssessMobility);
			return;
		}
	}
	
	protected void checkMovementPartOfAssessment()
	{
		//we only want to check if it belongs to an assessment if its outside the assessment form
		if(!engine.getPreviousNonDialogFormName().equals(form.getForms().COE.AssessMobility))
		{
			if(form.layerControl1().movement().comboAllMovements().getValue()!= null)
			{
				try
				{
					if(domain.isMovementPartOfMobilityAss(form.layerControl1().movement().comboAllMovements().getValue()).equals(Boolean.TRUE))
						form.layerControl1().movement().btnUpdateMovement().setEnabled(false);	
					else
						form.layerControl1().movement().btnUpdateMovement().setEnabled(true);
					
				} catch (DomainInterfaceException e)
				{
					engine.showMessage("Error retrieving movement assessment record: " + e.getMessage());
					return;
				}
			}
		}
	}
	
	protected void checkHandlingPartOfAssessment()
	{
		//we only want to check if it belongs to an assessment, i.e. if its outside the assessment form
		if(!engine.getPreviousNonDialogFormName().equals(form.getForms().COE.AssessMobility))
		{
			if(form.layerControl1().screening().comboAllScreening().getValue()!= null)
			{
				try
				{
					if(domain.isHandlingPartOfMobilityAss(form.layerControl1().screening().comboAllScreening().getValue()).equals(Boolean.TRUE))
						form.layerControl1().screening().btnUpdateScreening().setEnabled(false);	
					else
						form.layerControl1().screening().btnUpdateScreening().setEnabled(true);
					
				} catch (DomainInterfaceException e)
				{
					engine.showMessage("Error retrieving handling assessment record: " + e.getMessage());
					return;
				}
			}
		}
	}

	protected void onlayerControl1TabChanged(LayerBridge tab) 
	{
		if (tab.getCaption().compareToIgnoreCase("Patient Screening") == 0)
		{
			showScreening(false);
		}
		else
		{
			showMovement(true);
		}
	}

	private void printReport()
	{
		if(form.layerControl1().movement().comboAllMovements().getValue() == null)
		{
			engine.showMessage("No Movement Record Selected");
			return;
		}
		
		
		String urlQueryServer = ConfigFlag.GEN.QUERY_SERVER_URL.getValue();
		String urlReportServer = ConfigFlag.GEN.REPORT_SERVER_URL.getValue();

		String[] obj = null;
		obj = domain.getReportAndTemplate(form.getGlobalContext().Core.getReportID(), form.getGlobalContext().Core.getTemplateID());
		
		if(obj == null || obj.length == 0)
		{
			engine.showMessage("Failed to retrieve the report and template !");
			return;
		}
		
		QueryBuilderClient client = new QueryBuilderClient(urlQueryServer, engine.getSessionId());
		
		client.addSeed(new SeedValue("PatientMovementHandling_id", form.layerControl1().movement().comboAllMovements().getValue().getID_Assessment(), Integer.class));
		client.addSeed(new SeedValue("PATIDTYPE", new Integer(PatIdType.CHARTNUM.getID()), Integer.class));
		
		String resultUrl = "";
		try
		{
			resultUrl = client.buildReportAsUrl(obj[0], obj[1], urlReportServer, QueryBuilderClient.PDF, "", 1);		
		} 
		catch (QueryBuilderClientException e1)
		{
			engine.showMessage("Error creating report: " + e1.getMessage());
			return;
		}
		
		engine.openUrl(resultUrl);
	}

	@Override
	protected void onFormDialogClosed(FormName formName, DialogResult result) throws PresentationLogicException
	{
		if(result.equals(DialogResult.OK) && formName.equals(form.getForms().Core.Reports))
		{
			printReport();
		}	
	}
	
}
