/FileExtraction/Java_unseen/IMS-MAXIMS_openMAXIMS/Source Library/openmaxims_workspace/Nursing/src/ims/nursing/forms/dailypatientprogress/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 Sinead McDermott using IMS Development Environment (version 1.45 build 2259.24726)
// Copyright (C) 1995-2006 IMS MAXIMS plc. All rights reserved.

package ims.nursing.forms.dailypatientprogress;

import java.util.ArrayList;

import ims.assessment.configuration.vo.AssessmentQuestionRefVoCollection;
import ims.assessment.helper.DailyPatientProgressHelper;
import ims.assessment.helper.UserAssessmentInstHelper;
import ims.assessment.helper.DailyPatientProgressHelper.ScoreAndImage;
import ims.assessment.instantiation.vo.PatientAssessmentRefVo;
import ims.assessment.vo.PatientAssessmentAnswerVo;
import ims.assessment.vo.PatientAssessmentAnswerVoCollection;
import ims.assessment.vo.PatientAssessmentDataVo;
import ims.assessment.vo.PatientAssessmentGroupVo;
import ims.assessment.vo.PatientAssessmentListVo;
import ims.assessment.vo.PatientAssessmentListVoCollection;
import ims.assessment.vo.PatientAssessmentQuestionVo;
import ims.assessment.vo.PatientAssessmentVo;
import ims.assessment.vo.UserAssessmentVo;
import ims.assessment.vo.lookups.AnswerStatus;
import ims.assessment.vo.lookups.DPPType;
import ims.core.admin.vo.CareContextRefVo;
import ims.core.vo.AnswerDetailsVo;
import ims.core.vo.AssessmentQuestionVo;
import ims.core.vo.AuthoringInformationVo;
import ims.core.vo.HcpLiteVo;
import ims.core.vo.lookups.PatientAssessmentStatusReason;
import ims.core.vo.lookups.UserDefinedAssessmentType;
import ims.domain.exceptions.StaleObjectException;
import ims.framework.Control;
import ims.framework.FormName;
import ims.framework.MessageButtons;
import ims.framework.MessageIcon;
import ims.framework.controls.DynamicGridCell;
import ims.framework.controls.DynamicGridColumn;
import ims.framework.controls.DynamicGridRow;
import ims.framework.controls.TreeNode;
import ims.framework.enumerations.Alignment;
import ims.framework.enumerations.DialogResult;
import ims.framework.enumerations.DynamicCellType;
import ims.framework.enumerations.FormMode;
import ims.framework.exceptions.PresentationLogicException;
import ims.framework.utils.Color;
import ims.framework.utils.Date;
import ims.framework.utils.DateTime;
import ims.nursing.forms.dailypatientprogress.GenForm.grdDevicesRow;
import ims.nursing.forms.dailypatientprogress.GenForm.grdSummaryRow;
import ims.nursing.vo.BradenScale;
import ims.nursing.vo.DailyPatientProgressSearchCriteriaVo;
import ims.nursing.vo.MUSTVo;
import ims.nursing.vo.PatientInvasiveDeviceShortVo;
import ims.nursing.vo.PatientInvasiveDeviceShortVoCollection;
import ims.nursing.vo.PlanOfCareVoCollection;
import ims.nursing.vo.RepositioningPlanVo;
import ims.utils.textile.Textile;
import ims.vo.ValueObject;
import ims.vo.interfaces.IDPPItem;
import ims.vo.interfaces.IPatientAssessmentData;

public class Logic extends BaseLogic
{
	public static final Integer IMAGE_COLUMN = new Integer(-1);
	public static final Integer ASSESSMENT_COLUMN = new Integer(-2);
	public static final Integer PROTOCOL_COLUMN = new Integer(-3);
	public static final Integer INITIALS_COLUMN = new Integer(-4);
	public static final Integer URL_COLUMN = new Integer(-5);

	//----------------- Handlers ----------------------------------
	protected void onFormOpen() throws ims.framework.exceptions.PresentationLogicException
	{
		initialize();
		
		//WDEV-19389 - start
		if (!(form.getGlobalContext().Core.getCurrentCareContextIsNotNull() && form.getGlobalContext().Nursing.getDailyPatientProgressSearchCriteriaIsNotNull() && form.getGlobalContext().Nursing.getDailyPatientProgressSearchCriteria().getCareContextIsNotNull() && form.getGlobalContext().Core.getCurrentCareContext().equals(form.getGlobalContext().Nursing.getDailyPatientProgressSearchCriteria().getCareContext())))
			form.getGlobalContext().Nursing.setDailyPatientProgressSearchCriteria(null);
		
		if (form.getGlobalContext().Nursing.getDailyPatientProgressSearchCriteriaIsNotNull())
		{
			setSearchCriteria(form.getGlobalContext().Nursing.getDailyPatientProgressSearchCriteria());
			search();
		}
		else
		{
			prepopulateRecordBrowser();
			open();
		}
		//WDEV-19389 - end
		
		//open();
	}
	
	private DailyPatientProgressSearchCriteriaVo getSearchCriteria()
	{
		DailyPatientProgressSearchCriteriaVo searchCriteria = new DailyPatientProgressSearchCriteriaVo();

		searchCriteria.setStartDate(form.dteStart().getValue());
		searchCriteria.setEndDate(form.dteEnd().getValue());
		searchCriteria.setCareContext(form.getGlobalContext().Core.getCurrentCareContext());

		return searchCriteria;
	}

	private void setSearchCriteria(DailyPatientProgressSearchCriteriaVo dailyPatientProgressSearchCriteriaVo) 
	{
		form.dteStart().setValue(dailyPatientProgressSearchCriteriaVo.getStartDate());
		form.dteEnd().setValue(dailyPatientProgressSearchCriteriaVo.getEndDate());
	}
	
	protected void onContextMenuItemClick(int menuItemID, Control sender) throws PresentationLogicException 
	{
		if(sender.equals(form.dynGridDetails()))
		{
			switch(menuItemID)
			{
				case GenForm.ContextMenus.GenericGrid.Add:
					break;
				case GenForm.ContextMenus.GenericGrid.View:
					break;
				case GenForm.ContextMenus.GenericGrid.Update:
					break;
			}
		}
		
		if(sender.equals(form.grdSummary()))
		{
			switch(menuItemID)
			{
				case GenForm.ContextMenus.DailyPatientProgressAssessment.View:
					viewAssessmentRecord();
				break;
			}
		}
	}

	protected void onFormModeChanged()
	{
		if(form.getMode().equals(FormMode.VIEW))
		{
			boolean isRecordSelected = form.recbrAssessment().getValue() != null;
			form.btnUpdate().setVisible(isRecordSelected);
			form.lnkDPP().setEnabled(false);
		}
	}
	protected void onBtnCancelClick() throws ims.framework.exceptions.PresentationLogicException
	{
		clearControlsAndContext();
		if(form.recbrAssessment().getValue() != null)
			onRecbrAssessmentValueChanged();
		form.setMode(FormMode.VIEW);
	}
	protected void onBtnSaveClick() throws ims.framework.exceptions.PresentationLogicException
	{
		if(save())
		{
			form.setMode(FormMode.VIEW);	
		}
	}

	protected void onBtnUpdateClick() throws ims.framework.exceptions.PresentationLogicException
	{
		form.setMode(FormMode.EDIT);
		openDPPDialog();
	}
	protected void onBtnNewClick() throws ims.framework.exceptions.PresentationLogicException
	{
		//set in the context the current Assessment
		UserAssessmentVo voUserAssessment = domain.getCurrentDPPUserAssessment(UserDefinedAssessmentType.DPP);
		if(voUserAssessment == null)
		{
			engine.showMessage("No 'Active' Daily Patient Progress record exists on the system.");
			return;
		}

		clearControlsAndContext();

		//get the POC records based on Assessment Questions from Configuration
		PlanOfCareVoCollection planOfCareColl = listPOCRecords(voUserAssessment);
		
		//Get a copy of the new assessment - get the configured Questions
		PatientAssessmentVo voNewPatientAssessment = getNewPatientAssessment(voUserAssessment);
		if(voNewPatientAssessment != null)
		{
			setPOCData(planOfCareColl, voNewPatientAssessment);
		}

		form.getGlobalContext().Nursing.setPatientAssessmentVo(voNewPatientAssessment);
		form.getGlobalContext().Nursing.setPlanOfCareCollection(planOfCareColl);
		form.getGlobalContext().Nursing.setUserAssessmentDPP(voUserAssessment);
		form.getGlobalContext().Nursing.setIsDppCompleted(Boolean.FALSE);
		
		form.setMode(FormMode.EDIT);
		
		openDPPDialog();
	}

	private PatientAssessmentVo getNewPatientAssessment(UserAssessmentVo voUserAssessment_latest)
	{
		if(voUserAssessment_latest == null)
			return null;
		
		ArrayList records = form.recbrAssessment().getValues();
		if(records != null && records.size() > 0)
		{
			//WDEV-1612 - Get the last saved record - which is the first in the record browser because we have listed the records in reverse chronological order
			Object lastPatientAssessment = records.get(0);
			if(lastPatientAssessment instanceof PatientAssessmentRefVo)
			{
				PatientAssessmentRefVo voPatAssRefVo = (PatientAssessmentRefVo)lastPatientAssessment;
				PatientAssessmentVo voLastPatientAssessment = domain.getPatientAssessment(voPatAssRefVo);
				UserAssessmentVo voLastUserAssessment = voLastPatientAssessment != null && voLastPatientAssessment.getAssessmentDataIsNotNull() ? voLastPatientAssessment.getAssessmentData().getUserAssessment() : null;
				//Check if the User Assessment didn't changed atherwise forget about it - but get the new configuration
				if(voUserAssessment_latest.equals(voLastUserAssessment)  == false)
					return null;
					
				//Get the last record an clone the Patient Assessment Questions
				PatientAssessmentVo voPatientAssessment = new PatientAssessmentVo();
				voPatientAssessment.setAssessmentData(copyAssessmentDataFromPreviousAssessment(voLastPatientAssessment));
				return voPatientAssessment; 
			}
		}
		
		return null;		
	}

	//Copy the Question instantiation (but not the answers)
	private PatientAssessmentDataVo copyAssessmentDataFromPreviousAssessment(PatientAssessmentVo voLastPatientAssessment)
	{
		if (voLastPatientAssessment == null || voLastPatientAssessment.getAssessmentData() == null)
			return null;
		PatientAssessmentDataVo voPatientAssessmentData = (PatientAssessmentDataVo) voLastPatientAssessment.getAssessmentData().clone();
		//Clear the ids
		if(voPatientAssessmentData != null)
		{
			voPatientAssessmentData.setID_PatientAssessmentData(null);
			for (int i = 0; voPatientAssessmentData.getAnswerGroupsIsNotNull() && i < voPatientAssessmentData.getAnswerGroups().size(); i++)
			{
				PatientAssessmentGroupVo voPatientAssessmentGroup = voPatientAssessmentData.getAnswerGroups().get(i);
				voPatientAssessmentGroup.setID_PatientAssessmentGroup(null);
				for (int j = 0; voPatientAssessmentGroup.getAssessmentAnswers() != null && j < voPatientAssessmentGroup.getAssessmentAnswers().size(); j++)
				{
					PatientAssessmentQuestionVo voPatientAssessmentQuestion = voPatientAssessmentGroup.getAssessmentAnswers().get(j);
					voPatientAssessmentQuestion.setID_PatientAssessmentQuestion(null);
					voPatientAssessmentQuestion.setPatientAnswers(new PatientAssessmentAnswerVoCollection());
					voPatientAssessmentQuestion.setIsPoc(null);
					voPatientAssessmentQuestion.setIsConfirmed(null);
					voPatientAssessmentQuestion.setIsRoleReadOnly(null);
				}
			}
		}

		return voPatientAssessmentData;
	}

	private void clearControlsAndContext()
	{
		form.treScores().clear();
		form.dynGridDetails().getRows().clear();
		clearControls();

		form.getGlobalContext().Nursing.setPatientAssessmentVo(null);
		form.getGlobalContext().Nursing.setPlanOfCareCollection(null);
		clearDPPQuestionGroupContext();
	}

	protected void onLnkDPPClick() throws PresentationLogicException
	{
		openDPPDialog();
	}

	protected void onFormDialogClosed(FormName formName, DialogResult result) throws PresentationLogicException
	{
		if(formName.equals(form.getForms().Nursing.DailyPatientProgressDlg) && result.equals(DialogResult.OK))
		{
			PatientAssessmentVo voPatientAssessment = form.getGlobalContext().Nursing.getPatientAssessmentVo();
			PlanOfCareVoCollection planOfCareColl = form.getGlobalContext().Nursing.getPlanOfCareCollection();
			setPOCData(planOfCareColl, voPatientAssessment);
			form.getGlobalContext().Nursing.setPatientAssessmentVo(voPatientAssessment);
			populateDetailsGrid(voPatientAssessment);
			displayScoreTotalInTree(voPatientAssessment);
		}
	}
	protected void onRecbrAssessmentValueChanged() throws PresentationLogicException
	{
		PatientAssessmentRefVo voPatAssRefVo = form.recbrAssessment().getValue();
		//Context User for RIE only
		form.getLocalContext().setSelectedRecord(voPatAssRefVo);
		
		clearDPPQuestionGroupContext();
		if(voPatAssRefVo != null)
		{
			PatientAssessmentVo voPatAssessment = domain.getPatientAssessment(voPatAssRefVo);
			setIsDppAdmissionAssessment(voPatAssessment);
			PlanOfCareVoCollection planOfCareColl = listPOCRecords(voPatAssessment);
			setPOCData(planOfCareColl, voPatAssessment);
			form.getGlobalContext().Nursing.setPatientAssessmentVo(voPatAssessment);
			form.getGlobalContext().Nursing.setPlanOfCareCollection(planOfCareColl);
			form.getGlobalContext().Nursing.setIsDppCompleted(voPatAssessment != null && voPatAssessment.getStatusIsNotNull() && voPatAssessment.getStatus().equals(PatientAssessmentStatusReason.COMPLETED)?Boolean.TRUE:Boolean.FALSE);
			
			populateDetailsGrid(voPatAssessment);
			displayScoreTotalInTree(voPatAssessment);
		}
		//start WDEV-13887
		else
		{
			clearControlsAndContext();
		}
		
		updateControlState();  
		//end
	}
	
	//start WDEV-13887
	private void updateControlState() 
	{
		if(form.getMode().equals(FormMode.VIEW))
		{
			boolean isRecordSelected = form.recbrAssessment().getValue() != null;
			form.btnUpdate().setVisible(isRecordSelected);
			form.lnkDPP().setEnabled(false);
		}
	}
	//end

	protected void onTreScoresTreeViewSelectionChanged(TreeNode node) throws PresentationLogicException
	{
		populateDetailsGrid(form.getGlobalContext().Nursing.getPatientAssessmentVo(), (Integer)node.getValue());
	}
	//----------------- End Handlers ----------------------------
	
	//------------- Private Methods -----------------------------
	private void initialize()
	{
		
		Date now = new Date();
		now.addDay(-7);
		
		form.dteStart().setValue(now);
		form.dteEnd().setValue(new Date());
		
		clearAllScreenForRIE();
		createDynamicGridColumns();
		//prepopulateRecordBrowser();
		populateInvasiveDeviceGrid();
		populateAssessmentGrid();
	}

	private void clearAllScreenForRIE()
	{
		clearScreen();
		form.dynGridDetails().clear();
		form.recbrAssessment().clear();
		form.dtimAuthoring().setValue(null);
		form.qmbAuthoring().setValue(null);
		form.treScores().clear();
		form.grdDevices().getRows().clear();
		form.grdSummary().getRows().clear();
	}
	
	private void prepopulateRecordBrowser()
	{
		form.recbrAssessment().clear();
		PatientAssessmentListVoCollection voColl = domain.listPatientAssessments(form.getGlobalContext().Core.getCurrentCareContext(), UserDefinedAssessmentType.DPP, form.dteStart().getValue(), form.dteEnd().getValue());
		
		//start WDEV-13871
		if (voColl.size() == 0)
		{
			engine.showMessage("No records match your search criteria.", "No data found", MessageButtons.OK, MessageIcon.WARNING);
		}
		//end
		
		//Flag the Admission Assessment Record
		form.getGlobalContext().Nursing.setIsDppAdmissionAssessmentAdded(getIsDppAdmissionAssessmentAdded(voColl));
		for (int i = 0; i < voColl.size(); i++)
		{
			PatientAssessmentListVo voPatAssList = voColl.get(i);
			addItemToRecordBrowser(voPatAssList);
		}
	}

	private void addItemToRecordBrowser(PatientAssessmentListVo voPatAssList)
	{
		form.recbrAssessment().newRow(voPatAssList, getAssessmentName(voPatAssList));
	}
	
	/*private void addItemToRecordBrowser(PatientAssessmentVo voPatAssList)
	{
		form.recbrAssessment().newRow(voPatAssList, getAssessmentName(voPatAssList));
	}*/

	private String getAssessmentName(IPatientAssessmentData voPatAss)
	{
		if(voPatAss != null)
		{
			StringBuffer sb = new StringBuffer();
			if(voPatAss.getAssessmentName() != null)
			{
				sb.append(voPatAss.getAssessmentName());
			}
			if(voPatAss.getAuthoringInfo() != null)
			{
				sb.append(" ");
				sb.append(voPatAss.getAuthoringInfo().toString(", "));
			}
			return sb.toString();

		}
		return "";
	}

	private void open() throws PresentationLogicException
	{
		if(form.recbrAssessment().getValue() != null)
		{
			onRecbrAssessmentValueChanged();	
		}
	}
	
	private void populateDetailsGrid(PatientAssessmentVo voPatAss)
	{
		populateDetailsGrid(voPatAss, null);
	}
	private void populateDetailsGrid(PatientAssessmentVo voPatAss, Integer score)
	{
		super.populateScreenFromData(voPatAss);
		form.dynGridDetails().getRows().clear();
		
		if(voPatAss == null)
			return;

		populateAuthoringInfoControls(voPatAss);

		int questionIndex = 1;
		for (int i = 0; i < voPatAss.getAssessmentData().getAnswerGroups().size(); i++)
		{
			PatientAssessmentGroupVo voPatAssessGroup = voPatAss.getAssessmentData().getAnswerGroups().get(i);
			if(voPatAssessGroup.getAssessmentAnswers() != null)
				voPatAssessGroup.getAssessmentAnswers().sort();
			for (int j = 0; j < voPatAssessGroup.getAssessmentAnswers().size(); j++)
			{
				PatientAssessmentQuestionVo voPatAssQuestion = voPatAssessGroup.getAssessmentAnswers().get(j);
				if(isStatusAnswered(voPatAssQuestion) && hasAnswers(voPatAssQuestion))
				{
					ScoreAndImage scoreImage = getHelper().getScoreImage(voPatAssQuestion);
					if(!isNotTheSameScoreRecord(score, scoreImage))
						continue;
					
					DynamicGridRow row = form.dynGridDetails().getRows().newRow();
					
					DynamicGridCell imageCell = row.getCells().newCell(getCellByIdentifier(IMAGE_COLUMN), DynamicCellType.IMAGE);
					if(scoreImage != null)
					{
						imageCell.setValue(scoreImage.getImage());
					}
					String text = getQuestionText(voPatAssQuestion, questionIndex);
					questionIndex++;
					
					DynamicGridCell assessmentCell = row.getCells().newCell(getCellByIdentifier(ASSESSMENT_COLUMN), DynamicCellType.WRAPTEXT);
					assessmentCell.setValue(text);
					assessmentCell.setTooltip(text);
					assessmentCell.setReadOnly(true);
					//TODO - try to set it bold
					//assessmentCell.setBold
					
					DynamicGridCell protocolCell = row.getCells().newCell(getCellByIdentifier(PROTOCOL_COLUMN), DynamicCellType.STRING);
					protocolCell.setValue(voPatAssQuestion.getAssessmentQuestion().getProtocol());
					protocolCell.setTooltip(voPatAssQuestion.getAssessmentQuestion().getProtocol());
					protocolCell.setReadOnly(true);
					
					DynamicGridCell initialsCell = row.getCells().newCell(getCellByIdentifier(INITIALS_COLUMN), DynamicCellType.STRING);
					initialsCell.setValue(getInitials(voPatAssQuestion));
					initialsCell.setTooltip(getInitialsTooltip(voPatAssQuestion));
					initialsCell.setReadOnly(true);
					
					String urlText = getUrlText(voPatAssQuestion);
					if(urlText != null && urlText.length() > 0)
					{
						DynamicGridCell urlCell = row.getCells().newCell(getCellByIdentifier(URL_COLUMN), DynamicCellType.IMAGEBUTTON);
						urlCell.setValue(form.getImages().Core.Information);
						urlCell.setTooltip(getUrlText(voPatAssQuestion));
						urlCell.setReadOnly(false);
					}
			
					if(voPatAssQuestion.getIsPocIsNotNull() && voPatAssQuestion.getIsPoc().booleanValue())
						row.setBackColor(Color.Beige);
					
					row.setValue(voPatAssQuestion);
				}
			}
		}
	}

	private void populateAuthoringInfoControls(PatientAssessmentVo voPatAss)
	{
		if(voPatAss != null)
		{
			if(voPatAss.getAuthoringInformationIsNotNull())
			{
				HcpLiteVo authoringHcp = voPatAss.getAuthoringInformation().getAuthoringHcp();
				if(authoringHcp != null)
				{
					form.qmbAuthoring().newRow(authoringHcp, authoringHcp.toString());
					form.qmbAuthoring().setValue(authoringHcp);
				}
				form.dtimAuthoring().setValue(voPatAss.getAuthoringInformation().getAuthoringDateTime());
			}
		}
	}

	private String getQuestionText(PatientAssessmentQuestionVo voPatAssessment, int questionIndex)
	{
		return UserAssessmentInstHelper.getDPPQuestionAndAnswers(voPatAssessment, questionIndex);
	}

	private boolean save() throws PresentationLogicException
	{
		PlanOfCareVoCollection voPlanOfCareColl = form.getGlobalContext().Nursing.getPlanOfCareCollection();
		String[] pocErrors = null;
		if(voPlanOfCareColl != null)
		{
			pocErrors = voPlanOfCareColl.validate();
		}
		
		PatientAssessmentVo voPatAss = form.getGlobalContext().Nursing.getPatientAssessmentVo();
		
		//start WDEV-13871
		if (voPatAss == null || voPatAss.getPatient()== null ||voPatAss.getAuthoringInformation()==null )  //WDEV-15427
		{
			engine.showMessage("No Assessment has been selected");
			return	false;
		}
		//end
		
		//Set Status to In Progress
		boolean isNewAssessment = voPatAss.getID_PatientAssessment() == null;
		if(isNewAssessment && voPatAss.getStatusIsNotNull() && voPatAss.getStatus().equals(PatientAssessmentStatusReason.NOTCOMMENCED))
		{
			voPatAss.setStatus(PatientAssessmentStatusReason.INPROGRESS);
		}
		
		String[] errors = voPatAss.validate(pocErrors);
		if(errors != null)
		{
			engine.showErrors(errors);
			return false;
		}
		try
		{
			IDPPItem dppItem = domain.savePatientAssessment(voPatAss, voPlanOfCareColl);
			if(dppItem != null)
			{
				displayNewPlanOfCareMessage(dppItem);
				//Add and Refresh Assessment
				if(isNewAssessment)
				{
					//Refresh Record Browser Again
					prepopulateRecordBrowser();
					//addItemToRecordBrowser(dppItem.getPatientAssessment());
					form.recbrAssessment().setValue(dppItem.getPatientAssessment());
				}
				onRecbrAssessmentValueChanged();
			}
		}
		catch (StaleObjectException e)
		{
			engine.showMessage(ims.configuration.gen.ConfigFlag.UI.STALE_OBJECT_MESSAGE.getValue());
			onRecbrAssessmentValueChanged(); 
			form.setMode(FormMode.VIEW);
			return false;
		}
		return true;
	}

	private void displayNewPlanOfCareMessage(IDPPItem dppItem)
	{
		if(dppItem.getNewPlanOfCareSaved() != null)
		{
			int newPlanOfCareSaved = dppItem.getNewPlanOfCareSaved().intValue();
			if(newPlanOfCareSaved != 0)
			{
				StringBuffer infoMsg = new StringBuffer();
				if(newPlanOfCareSaved > 1)
				{
					infoMsg.append(Integer.toString(newPlanOfCareSaved));
					infoMsg.append(" Plans of Care have been created");
				}
				else
				{
					infoMsg.append(Integer.toString(newPlanOfCareSaved));
					infoMsg.append(" Plan of Care has been created");
				}
				
				engine.showMessage(infoMsg.toString());
			}
		}
	}

	private void displayScoreTotalInTree(PatientAssessmentVo voPatAssessment)
	{
		form.treScores().clear();
		if(voPatAssessment == null)
			return;
		
		DailyPatientProgressHelper helper = getHelper();
		helper.populateTreeScores(form.treScores(), voPatAssessment.getAssessmentData().getAnswerGroups());
	}

	private void clearControls()
	{
		super.clearScreen();
		form.qmbAuthoring().clear();
		form.dtimAuthoring().setValue(null);
	}
	
	private String getInitials(PatientAssessmentQuestionVo voPatAssessment)
	{
		if(voPatAssessment == null)
			return null;
		
		StringBuffer text = new StringBuffer();
		
		AuthoringInformationVo voAuthoringInfoVo = getAuthoringInfoForMultiSelectAnswer(voPatAssessment);
		if(voAuthoringInfoVo != null)
		{
			HcpLiteVo hcp = voAuthoringInfoVo.getAuthoringHcp();
			if(hcp != null)
			{
				text.append(hcp.getMosIsNotNull() && hcp.getMos().getInitialsIsNotNull()?hcp.getMos().getInitials() + " ":"");
			}
		}
		
		if(hasMultipleAnswers(voPatAssessment.getPatientAnswers()))
		{
			text.append("/* ");
		}
		
		if(isConfirmed(voPatAssessment) == false)
			text.append("/***");
				
		return text.toString();
	}

	private boolean isNotTheSameScoreRecord(Integer score, ScoreAndImage scoreImage)
	{
		if(score != null && scoreImage != null && scoreImage.getHighestScore() != null)
		{
			if(score.intValue() != scoreImage.getHighestScore().intValue())
			{
				return false;
			}
		}
		
		return true;
	}
	
	private boolean isStatusAnswered(PatientAssessmentQuestionVo voPatAssQuestion)
	{
		return voPatAssQuestion != null && voPatAssQuestion.getIsAnsweredIsNotNull() && voPatAssQuestion.getIsAnswered().equals(AnswerStatus.ANSWERED);
	}
	
	private boolean hasAnswers(PatientAssessmentQuestionVo voAssessQuestion)
	{
		if(voAssessQuestion == null)
			return false;
		
		for (int i = 0; i < voAssessQuestion.getPatientAnswers().size(); i++)
		{
			for (int j = 0; j < voAssessQuestion.getPatientAnswers().get(i).getAnswerDetails().size(); j++)
			{
				AnswerDetailsVo answerDetail = voAssessQuestion.getPatientAnswers().get(i).getAnswerDetails().get(j);
				if(isMultiSelectAnswer(answerDetail))
				{
					return answerDetail.getMultiSelectAnswers().size() > 0;
				}
			}
		}
		return false;
	}

	private boolean isMultiSelectAnswer(AnswerDetailsVo answerDetail)
	{
		ims.core.vo.lookups.QuestionAnswerType questionAnswerType = answerDetail.getAnswerTypeIsNotNull() ? answerDetail.getAnswerType().getAnswerType():null;
		return questionAnswerType != null && questionAnswerType.equals(ims.core.vo.lookups.QuestionAnswerType.MULTISELECT);
	}
	
	private PatientAssessmentAnswerVo getMultiSelectAnswer(PatientAssessmentQuestionVo voAssessQuestion)
	{
		if(voAssessQuestion == null)
			return null;
		
		for (int i = 0; i < voAssessQuestion.getPatientAnswers().size(); i++)
		{
			for (int j = 0; j < voAssessQuestion.getPatientAnswers().get(i).getAnswerDetails().size(); j++)
			{
				AnswerDetailsVo answerDetail = voAssessQuestion.getPatientAnswers().get(i).getAnswerDetails().get(j);
				if(isMultiSelectAnswer(answerDetail))
				{
					return voAssessQuestion.getPatientAnswers().get(i);
				}
			}
		}
		return null;
	}
	
	private AuthoringInformationVo getAuthoringInfoForMultiSelectAnswer(PatientAssessmentQuestionVo voAssessQuestion)
	{
		if(voAssessQuestion == null)
			return null;
		
		for (int i = 0; i < voAssessQuestion.getPatientAnswers().size(); i++)
		{
			for (int j = 0; j < voAssessQuestion.getPatientAnswers().get(i).getAnswerDetails().size(); j++)
			{
				AnswerDetailsVo answerDetail = voAssessQuestion.getPatientAnswers().get(i).getAnswerDetails().get(j);
				if(isMultiSelectAnswer(answerDetail))
				{
					return voAssessQuestion.getPatientAnswers().get(i).getAuthoringInfo();
				}
			}
		}
		return null;
	}
	
	private boolean isConfirmed(PatientAssessmentQuestionVo voAssessQuestion)
	{
		if(voAssessQuestion == null)
			return false;
		
		for (int i = 0; i < voAssessQuestion.getPatientAnswers().size(); i++)
		{
			for (int j = 0; j < voAssessQuestion.getPatientAnswers().get(i).getAnswerDetails().size(); j++)
			{
				AnswerDetailsVo answerDetail = voAssessQuestion.getPatientAnswers().get(i).getAnswerDetails().get(j);
				if(isMultiSelectAnswer(answerDetail))
				{
					return voAssessQuestion.getPatientAnswers().get(i).getConfirmingInfoIsNotNull();
				}
			}
		}
		return false;
	}
	
	private DailyPatientProgressHelper getHelper()
	{
		return new DailyPatientProgressHelper(form.getImages().Core.RedSqaure, form.getImages().Core.YellowSquare, form.getImages().Core.GreenSquare);
	}
	
	private PlanOfCareVoCollection listPOCRecords(UserAssessmentVo voUserAssessment)
	{
		AssessmentQuestionRefVoCollection assQRefVoColl = getAssessmentQuestions(voUserAssessment);
		return domain.listPlanOfCare(form.getGlobalContext().Core.getCurrentCareContext(), assQRefVoColl);
	}
	
	private PlanOfCareVoCollection listPOCRecords(PatientAssessmentVo voPatAssessment)
	{
		AssessmentQuestionRefVoCollection assQRefVoColl = getAssessmentQuestions(voPatAssessment);
		return domain.listPlanOfCare(form.getGlobalContext().Core.getCurrentCareContext(), assQRefVoColl);
	}

	private AssessmentQuestionRefVoCollection getAssessmentQuestions(PatientAssessmentVo voPatAssessment)
	{
		AssessmentQuestionRefVoCollection voColl = new AssessmentQuestionRefVoCollection();
		for (int i = 0; voPatAssessment != null && i < voPatAssessment.getAssessmentData().getAnswerGroups().size(); i++)
		{
			for (int j = 0; j < voPatAssessment.getAssessmentData().getAnswerGroups().get(i).getAssessmentAnswers().size(); j++)
			{
				voColl.add(voPatAssessment.getAssessmentData().getAnswerGroups().get(i).getAssessmentAnswers().get(j).getAssessmentQuestion());
			}
		}

		return voColl;
	}
	
	private AssessmentQuestionRefVoCollection getAssessmentQuestions(UserAssessmentVo voUserAssessment)
	{
		AssessmentQuestionRefVoCollection voColl = new AssessmentQuestionRefVoCollection();
		for (int i = 0; voUserAssessment != null && i < voUserAssessment.getQuestionGroups().size(); i++)
		{
			for (int j = 0; j < voUserAssessment.getQuestionGroups().get(i).getQuestions().size(); j++)
			{
				voColl.add(voUserAssessment.getQuestionGroups().get(i).getQuestions().get(j));
			}
		}
		return voColl;
	}
	
	private void setPOCData(PlanOfCareVoCollection pocVoColl, PatientAssessmentVo voPatAssessment)
	{
		if(voPatAssessment == null)
			return;
		PatientAssessmentDataVo assessmentData = voPatAssessment.getAssessmentData();
		if(assessmentData == null)
			return;
		for (int i = 0; i < assessmentData.getAnswerGroups().size(); i++)
		{
			for (int j = 0; j < assessmentData.getAnswerGroups().get(i).getAssessmentAnswers().size(); j++)
			{
				PatientAssessmentQuestionVo voPatAssQuestionVo = assessmentData.getAnswerGroups().get(i).getAssessmentAnswers().get(j);
				voPatAssQuestionVo.setIsPoc(getPocValue(voPatAssQuestionVo.getAssessmentQuestion(), pocVoColl));
				assessmentData.getAnswerGroups().get(i).getAssessmentAnswers().set(j, voPatAssQuestionVo);
			}
		}
	}
	private Boolean getPocValue(AssessmentQuestionVo assessmentQuestion, PlanOfCareVoCollection pocVoColl)
	{
		if(assessmentQuestion == null )
			return Boolean.FALSE;

		for (int i = 0; pocVoColl != null && i < pocVoColl.size(); i++)
		{
			if(pocVoColl.get(i).getAssessmentQuestionIsNotNull() && pocVoColl.get(i).getAssessmentQuestion().equals(assessmentQuestion))
				return Boolean.TRUE;
		}
		return Boolean.FALSE;
	}
	
	private void openDPPDialog()
	{
		boolean firstRecord = form.recbrAssessment().getValues().size() == 0;
		form.getGlobalContext().Nursing.setIsFirstDppInstantiation(new Boolean(firstRecord));
		engine.open(form.getForms().Nursing.DailyPatientProgressDlg);
	}

	private void clearDPPQuestionGroupContext()
	{
		form.getGlobalContext().Nursing.clearDPPQuestionGroupListVoCollection();
	}
	
	private void populateInvasiveDeviceGrid()
	{
		PatientInvasiveDeviceShortVoCollection voColl = domain.listCurrentPatientInvasiveDevice(form.getGlobalContext().Core.getCurrentCareContext());
		for (int i = 0; voColl != null && i < voColl.size(); i++)
		{
			PatientInvasiveDeviceShortVo voInvasiveDev = voColl.get(i);
			grdDevicesRow row = form.grdDevices().getRows().newRow();
			row.setColType(voInvasiveDev.getInvasiveDeviceIsNotNull()?voInvasiveDev.getInvasiveDevice().getInvasiveDevice():"");
			row.setColInserted(voInvasiveDev.getInsertedDateTimeIsNotNull()?voInvasiveDev.getInsertedDateTime().toString():"");
			if (voInvasiveDev.getTargetRemovalDateTime().getDate().isLessOrEqualThan(new DateTime().getDate()))
			{
				row.setBackColor(ims.configuration.gen.ConfigFlag.UI.INVASIVE_DEVICE_REMOVAL_ROW_COLOR.getValue());
			}
		}
	}
	
	private void populateAssessmentGrid()
	{
		populateBradenScaleRecord();
		populateMustRecord();
		populateSkinAssessmentRecord();
		populatePainAssessmentRecord();
		populateFallsAssessment();
		populateResositioningPlanningRecord();
	}

	private void populateBradenScaleRecord()
	{
		CareContextRefVo careContextRefVo = form.getGlobalContext().Core.getCurrentCareContext();
		BradenScale bradenScaleVo = domain.getLastCompletedBradenScale(careContextRefVo);
		if (bradenScaleVo != null)
		{
			addNewAssessmentRow(bradenScaleVo, "Braden Scale", bradenScaleVo.getDateTimeInitiated());
		}
	}
	
	private void populateMustRecord()
	{
		CareContextRefVo careContextRefVo = form.getGlobalContext().Core.getCurrentCareContext();
		MUSTVo mustVo = domain.getLastComplementedMustRecord(careContextRefVo);
		if(mustVo != null)
		{
			addNewAssessmentRow(mustVo, "MUST", mustVo.getAuthoringInformationIsNotNull()?mustVo.getAuthoringInformation().getAuthoringDateTime():null);
		}
	}
	
	private void populatePainAssessmentRecord()
	{
		PatientAssessmentListVo painAssessment = domain.getLastCompletedAssessment(UserDefinedAssessmentType.PAINASSESSMENT, form.getGlobalContext().Core.getCurrentCareContext(), Boolean.TRUE);
		if (painAssessment != null)
		{
			addNewAssessmentRow(painAssessment, "Pain Assessment", painAssessment.getAuthoringInformationIsNotNull() ? painAssessment.getAuthoringInformation().getAuthoringDateTime() : null);
		}
	}
	
	private void populateFallsAssessment()
	{
		PatientAssessmentListVo fallAssessment = domain.getLastStructuredAssessment(UserDefinedAssessmentType.FALLSRISK, form.getGlobalContext().Core.getCurrentCareContext());
		if (fallAssessment != null)
		{
			addNewAssessmentRow(fallAssessment, UserDefinedAssessmentType.FALLSRISK.toString(), fallAssessment.getAuthoringInformationIsNotNull() ? fallAssessment.getAuthoringInformation().getAuthoringDateTime() : null);
		}	
	}

	private void populateSkinAssessmentRecord()
	{
		PatientAssessmentListVo skinAssessment = domain.getLastCompletedAssessment(UserDefinedAssessmentType.SKINASSESSMENT, form.getGlobalContext().Core.getCurrentCareContext(), Boolean.TRUE);
		if (skinAssessment != null)
		{
			addNewAssessmentRow(skinAssessment, UserDefinedAssessmentType.SKINASSESSMENT.toString(), skinAssessment.getAuthoringInformationIsNotNull() ? skinAssessment.getAuthoringInformation().getAuthoringDateTime() : null);
		}
	}
	
	private void populateResositioningPlanningRecord()
	{
		RepositioningPlanVo voRepositioningPlan = domain.getLastCompletedRepositioningPlan(form.getGlobalContext().Core.getCurrentCareContext());
		if(voRepositioningPlan != null)
		{
			addNewAssessmentRow(voRepositioningPlan, "Repositioning Plan", voRepositioningPlan.getAuthoringInformationIsNotNull()?voRepositioningPlan.getAuthoringInformation().getAuthoringDateTime():null);
		}
	}
	
	private void addNewAssessmentRow(ValueObject genericVo, String assessment, DateTime dateTimeInitiated)
	{
		grdSummaryRow row = form.grdSummary().getRows().newRow();
		row.setColAssessment(assessment);
		row.setColLastCompleted(dateTimeInitiated != null ? dateTimeInitiated.toString() : "");
		row.setValue(genericVo);		
	}
	
	private void viewAssessmentRecord()
	{
		Object value = form.grdSummary().getValue();
		if (value instanceof BradenScale)
		{
			engine.open(form.getForms().Nursing.BradenScaleVIEW);
		}
		if (value instanceof MUSTVo)
		{
			engine.open(form.getForms().Nursing.MUST);
		}

		if (value instanceof PatientAssessmentListVo)
		{
			PatientAssessmentListVo voPatAsssess = (PatientAssessmentListVo) value;
			UserDefinedAssessmentType userDefinedAssessmentType = null;
			if (voPatAsssess.getAssessmentDataIsNotNull() && voPatAsssess.getAssessmentData().getGraphicIsNotNull())
				userDefinedAssessmentType = voPatAsssess.getAssessmentData().getGraphic().getAssessmentType();
			if (userDefinedAssessmentType != null)
			{
				if (userDefinedAssessmentType.equals(UserDefinedAssessmentType.PAINASSESSMENT))
					engine.open(form.getForms().Assessment.PatientGraphicStagesPain);
				else if (userDefinedAssessmentType.equals(UserDefinedAssessmentType.SKINASSESSMENT))
					engine.open(form.getForms().Assessment.PatientGraphicStages);
			}
		}
		
		if(value instanceof RepositioningPlanVo)
		{
			engine.open(form.getForms().Nursing.RepositioningPlan);
		}
	}
	
	
	private Boolean getIsDppAdmissionAssessmentAdded(PatientAssessmentListVoCollection voColl)
	{
		for (int i = 0; voColl != null && i < voColl.size(); i++)
		{
			PatientAssessmentListVo voPatAssList = voColl.get(i);
			DPPType dppType = voPatAssList.getDPPType();
			if(dppType != null && dppType.equals(DPPType.ADMISSION))
				return Boolean.TRUE;
		}
		
		return Boolean.FALSE;
	}
	
	private void setIsDppAdmissionAssessment(PatientAssessmentVo voPatAssessment)
	{
		if(voPatAssessment != null)
		{
			DPPType dppType = voPatAssessment.getDPPType();
			if(dppType != null && dppType.equals(DPPType.ADMISSION))
				form.getGlobalContext().Nursing.setIsDppAdmissionAssessmentAdded(Boolean.TRUE);
		}
	}
	
	private void createDynamicGridColumns()
	{
		form.dynGridDetails().clear();
		DynamicGridColumn imageColumn = form.dynGridDetails().getColumns().newColumn("", IMAGE_COLUMN);
		imageColumn.setWidth(20);
		
		DynamicGridColumn assessmentColumn = form.dynGridDetails().getColumns().newColumn("Current Assessment - Daily Patient Progress", ASSESSMENT_COLUMN);
		assessmentColumn.setWidth(450);
		assessmentColumn.setReadOnly(true);
		assessmentColumn.setCanGrow(true);
		
		DynamicGridColumn protocolColumn = form.dynGridDetails().getColumns().newColumn("Protocol", PROTOCOL_COLUMN);
		protocolColumn.setWidth(120);
		protocolColumn.setReadOnly(true);
		
		DynamicGridColumn initialsColumn = form.dynGridDetails().getColumns().newColumn("Initials", INITIALS_COLUMN);
		initialsColumn.setWidth(120);
		initialsColumn.setReadOnly(true);
		
		DynamicGridColumn urlColumn = form.dynGridDetails().getColumns().newColumn("", URL_COLUMN);
		urlColumn.setWidth(-1);
		urlColumn.setReadOnly(false);
		urlColumn.setAlignment(Alignment.CENTER);
	}

	protected void onGrdDetailsCellButtonClicked(DynamicGridCell cell)
	{
		if (cell != null && cell.getType().equals(DynamicCellType.IMAGEBUTTON))
		{
			if(cell.getRow().getValue() instanceof PatientAssessmentQuestionVo)
			{
				PatientAssessmentQuestionVo voPatAssQuestion = (PatientAssessmentQuestionVo)cell.getRow().getValue();
				String url = getUrlText(voPatAssQuestion);
				if(url != null && url.length() > 0)
				{
					engine.openUrl(url);
				}		
			}
		}
	}
	
	private String getUrlText(PatientAssessmentQuestionVo voPatAssQuestion)
	{
		return voPatAssQuestion.getAssessmentQuestionIsNotNull()?voPatAssQuestion.getAssessmentQuestion().getURL():"";
	}

	private DynamicGridColumn getCellByIdentifier(Integer columnIdentifier)
	{
		return form.dynGridDetails().getColumns().getByIdentifier(columnIdentifier);
	}
	
	private boolean hasMultipleAnswers(PatientAssessmentAnswerVoCollection patientAnswers)
	{
		if(patientAnswers != null)
		{
			for (int i = 0; i < patientAnswers.size(); i++)
			{
				for (int j = 0; j < patientAnswers.get(i).getAnswerDetails().size(); j++)
				{
					if(patientAnswers.get(i).getAnswerDetails().get(j).getMultiSelectAnswersIsNotNull() && patientAnswers.get(i).getAnswerDetails().get(j).getMultiSelectAnswers().size() > 1)
						return true;
				}
			}
		}
		return false;
	}
	
	private String getInitialsTooltip(PatientAssessmentQuestionVo voPatAssQuestion)
	{
		if (voPatAssQuestion != null && voPatAssQuestion.getPatientAnswers().size() > 0)
		{
			StringBuffer tooltip = new StringBuffer();
			PatientAssessmentAnswerVo voPatAssessmentAnswer = getMultiSelectAnswer(voPatAssQuestion);
			if (voPatAssessmentAnswer != null)
			{
				AuthoringInformationVo voAuthoring = voPatAssessmentAnswer.getAuthoringInfo();
				if (voAuthoring != null)
				{
					tooltip.append("*Authoring Information:* ");
					tooltip.append(voAuthoring.toString(", "));
				}
				AuthoringInformationVo voConfirming = voPatAssessmentAnswer.getConfirmingInfo();
				if (voConfirming != null)
				{
					tooltip.append("\n");
					tooltip.append("*Confirming Information:* ");
					tooltip.append(voConfirming.toString(", "));
				}
				return new Textile().process(tooltip.toString());
			}
		}
		return "";
	}

	@Override
	protected void onImbSearchClick() throws PresentationLogicException 
	{ 
		if(search())
			form.getGlobalContext().Nursing.setDailyPatientProgressSearchCriteria(getSearchCriteria());//WDEV-19389 
	}

	private boolean search()
	{
		if (validateSearchCriteria()) //WDEV-13871
		{
			prepopulateRecordBrowser();
			try
			{
				onRecbrAssessmentValueChanged();//WDEV-13887 
			}
			catch (PresentationLogicException e)
			{
				e.printStackTrace();
			} 
			return true;
		}
		return false;
	}

	//start WDEV-13871
	private boolean validateSearchCriteria() 
	{
		ArrayList<String> uiErrors = new ArrayList<String>();
		Date dateStart = form.dteStart().getValue();
		Date dateEnd = form.dteEnd().getValue();
		
		if (dateStart != null && dateEnd != null && dateEnd.isLessThan(dateStart))
		{
			uiErrors.add("Start Date cannot be greater than End Date."); //WDEV-18762
		}
		
		if (uiErrors.size() > 0)
		{
			engine.showErrors(uiErrors.toArray(new String[uiErrors.size()]));
			return false;
		}
		return true;
	}
	//end

	// ------------- End Private Methods -------------------------
}
