//#############################################################################
//#                                                                           #
//#  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 John Pearson using IMS Development Environment (version 1.18 build 40628.1300)
// Copyright (C) 1995-2004 IMS MAXIMS plc. All rights reserved.

package ims.nursing.forms.careplandetails;

import ims.coe.vo.Discharge;
import ims.configuration.AppRight;
import ims.configuration.gen.ConfigFlag;
import ims.core.vo.AuthoringInformationVo;
import ims.core.vo.ClinicalNotesVo;
import ims.core.vo.HcpLiteVo;
import ims.core.vo.MemberOfStaffShortVo;
import ims.domain.exceptions.DomainInterfaceException;
import ims.domain.exceptions.DomainRuntimeException;
import ims.domain.exceptions.StaleObjectException;
import ims.framework.Control;
import ims.framework.MessageButtons;
import ims.framework.MessageIcon;
import ims.framework.controls.DynamicGridCell;
import ims.framework.controls.DynamicGridColumn;
import ims.framework.controls.DynamicGridColumnCollection;
import ims.framework.controls.DynamicGridRow;
import ims.framework.enumerations.DialogResult;
import ims.framework.enumerations.DynamicCellType;
import ims.framework.enumerations.FormMode;
import ims.framework.enumerations.SortOrder;
import ims.framework.exceptions.FormOpenException;
import ims.framework.exceptions.PresentationLogicException;
import ims.framework.utils.Color;
import ims.framework.utils.Date;
import ims.framework.utils.DateTime;
import ims.nursing.careplans.vo.CarePlanRefVo;
import ims.nursing.vo.CarePlan;
import ims.nursing.vo.CarePlanCollection;
import ims.nursing.vo.CarePlanEvaluationNote;
import ims.nursing.vo.CarePlanEvaluationNoteCollection;
import ims.nursing.vo.CarePlanInterventions;
import ims.nursing.vo.CarePlanInterventionsCollection;
import ims.nursing.vo.CarePlanReviewHistory;
import ims.nursing.vo.CarePlanReviewHistoryCollection;
import ims.nursing.vo.CarePlanStatus;
import ims.nursing.vo.CarePlanStatusCollection;
import ims.nursing.vo.CarePlanTemplate;
import ims.nursing.vo.CarePlanTemplateIntervention;
import ims.nursing.vo.CarePlanTemplateInterventionCollection;
import ims.nursing.vo.NursingClinicalNotesVoCollection;
import ims.nursing.vo.lookups.CarePlanInterventionManOpt;

import java.util.ArrayList;
import java.util.List;

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

public class Logic extends BaseLogic
{
	private static final Integer SELECTED_COLUMN_INDENTIFIER = -1;
	private static final int SELECTED_COLUMN_WIDTH = 55;
	private static final Integer ACTION_COLUMN_INDENTIFIER = -2;
	private static final int[] ACTION_COLUMN_WIDTHS = {550,350,350,250};		//wdev-13285
	private static final Integer STARTD_COLUMN_INDENTIFIER = -3;
	private static final int STARTD_COLUMN_WIDTH = 70;							//wdev-13285
	private static final Integer STARTB_COLUMN_INDENTIFIER = -4;
	private static final int[] STARTB_COLUMN_WIDTH = {-1,130};					//wdev-13285
	private static final Integer STOPD_COLUMN_INDENTIFIER = -5;
	private static final int STOPD_COLUMN_WIDTH = 70;							//wdev-13285
	private static final Integer STOPB_COLUMN_INDENTIFIER = -6;
	private static final int[] STOPB_COLUMN_WIDTH = {-1,130};					//wdev-13285
	private static final Integer NOTES_COLUMN_INDENTIFIER = -7;
	private static final int NOTES_COLUMN_WIDTH = -1;
	
	private static final Integer REMOVE_ACTION_MESSAGEBOX = -17;
	private static final Integer REINSTATE_ACTION_MESSAGEBOX = -18;
	
	
	protected void onFormOpen() throws ims.framework.exceptions.FormOpenException
	{
		if (!form.getGlobalContext().COE.getCarePlanIDIsNotNull())
		{
			throw new FormOpenException("Error occurred getting CarePlan - cannot load form");
		}
		initialize();
		open();	

	}


	@Override
	protected void onMessageBoxClosed(int messageBoxId, DialogResult result) throws PresentationLogicException
	{
		if (REMOVE_ACTION_MESSAGEBOX.equals(form.getLocalContext().getMessageBoxClosed()) && result.equals(DialogResult.YES)) //WDEV-14324 
		{
			form.getLocalContext().setMessageBoxClosed(null);
			removeAction(true);
			updateControlState();
			return;
		}
		
		if (REINSTATE_ACTION_MESSAGEBOX.equals(form.getLocalContext().getMessageBoxClosed()) && result.equals(DialogResult.YES)) //WDEV-14324 
		{
			form.getLocalContext().setMessageBoxClosed(null);
			removeAction(false);
			updateControlState();
			return;
		}
	}
	

	private void removeAction(boolean remove)
	{
		loadCarePlanFromScreen();

		CarePlanInterventions value = (CarePlanInterventions)form.dyngrdActions().getSelectedRow().getValue();
		
		value.setIsRemoved(remove);
		//WDEV-16795 ------------------ start
		AuthoringInformationVo authoringInfo = populateAuthoringInfo();
		value.setRemovalAuthoringInformation(remove ? authoringInfo : null);
		value.setReinstatingAuthoringInformation(remove ? null : authoringInfo); 
		//WDEV-16795 ------------------- end		
		populateDynGrid(form.getLocalContext().getCarePlan().getInterventions());
	}

	//WDEV-16795
	private AuthoringInformationVo populateAuthoringInfo()
	{
		AuthoringInformationVo authoringInfo = new AuthoringInformationVo();
		authoringInfo.setAuthoringHcp((HcpLiteVo) domain.getHcpLiteUser());
		authoringInfo.setAuthoringDateTime(new DateTime());
		
		return authoringInfo;
	}


	private void open() 
	{
		CarePlan cp = new CarePlan();
		CarePlanCollection tempColl = null;
		cp.setID_CarePlan(form.getGlobalContext().COE.getCarePlanID());
		try
		{
			
			tempColl = domain.listCarePlans(cp); //wdev-13495 
			//cp = domain.getCarePlan(cp);
			if(tempColl != null && tempColl.size() > 0)	//wdev-13495
			{
				cp = tempColl.get(0);
			}
			else
			{
				cp = null;
			}
			
		}
		catch (DomainInterfaceException e)
		{
			throw new DomainRuntimeException("DomainInterfaceException occurred getting careplan " + e.getMessage(), e);
		}

		if(cp==null){
			try {
				onBCancelClick();
			} catch (PresentationLogicException e) {
				e.printStackTrace();
			}
			return;
		}
			
		// need to store cp here as it's required in the care plan dialog
		form.getGlobalContext().COE.setCarePlan(cp);
		form.getLocalContext().setCarePlan(cp);
		if(cp.getCurrentCarePlanStatusIsNotNull())
			form.getLocalContext().setCarePlanStatus(cp.getCurrentCarePlanStatus().getStatus());
		
		form.textTitle().setValue(cp.getTitle());
		form.textObjective().setValue(cp.getObjective());
		form.textObjective().setTooltip(returnMultilineString(cp.getObjective()));
		
		if(cp.getInterventionsIsNotNull()) //wdev-13495
			cp.getInterventions().sort();

		populateDynGrid(cp.getInterventions());
		
		populateNotesGrid(cp);
		form.bSave().setEnabled(true);
		form.bSave().setVisible(false);
		form.btnCancel().setVisible(false);
		form.bClose().setVisible(true);
		form.bClose().setEnabled(true);
		
		form.bEval().setEnabled(false);
		
		

		if (cp.getCurrentCarePlanStatusIsNotNull()
			&& cp.getCurrentCarePlanStatus().getStatusIsNotNull()
			&& (cp.getCurrentCarePlanStatus().getStatus().equals(ims.nursing.vo.lookups.CarePlanStatus.COMPLETE) 
					|| cp.getCurrentCarePlanStatus().getStatus().equals(ims.nursing.vo.lookups.CarePlanStatus.DISCONTINUED)))
		{
			form.bUpdate().setEnabled(false);
			form.lnkClinicalNote().setEnabled(false);
			form.btnReviewHistory().setVisible(true);
		}
		else
		{
			form.btnReviewHistory().setVisible(false);
		}

		
		form.setMode(FormMode.VIEW);
		updateControlState();
	}
	
	private String returnMultilineString(String str)
	{
		String temp = new String();
		if(str == null || str.length() == 0)
			return null;
				
		for(int i = 0; i < str.length();i++)
		{
			temp = temp + str.charAt(i);
			if(i != 0 && i % 100 == 0)
				temp = temp + "<br>";
		
		}
		return temp;
	}

	private void populateDynGrid(CarePlanInterventionsCollection interventions)
	{
		
		form.dyngrdActions().getRows().clear();
		form.dyngrdActions().setValue(null);
		if (interventions == null)
			return;
		 for (int i = 0 ; i < interventions.size() ;  i++)
		 {
			 if (shouldAdd(interventions.get(i)))
			 {
				 DynamicGridRow newRow = form.dyngrdActions().getRows().newRow();
				 populateDynGridRowFromData( newRow,interventions.get(i));
			 }
		 }
		
	}
	private void updateControlState()
	{
		boolean isCcoSpecific = ConfigFlag.GEN.CARE_PLAN_FUNCTIONALITY_TYPE.getValue().equals("CCO");
		boolean isEditMode = FormMode.EDIT.equals(form.getMode());
		
		//WDEV-15252
		form.lnkReturnToCarePlanWorklist().setVisible(!isEditMode && engine.getPreviousNonDialogFormName().equals(form.getForms().Nursing.CarePlanWorklist));
		
		if (isEditMode)
		{
			form.cbFilter().setEnabled(isCcoSpecific);
		}
		else
		{
			ims.nursing.vo.lookups.CarePlanStatus cStatus = form.getLocalContext().getCarePlanIsNotNull() && form.getLocalContext().getCarePlan().getCurrentCarePlanStatusIsNotNull() ? form.getLocalContext().getCarePlan().getCurrentCarePlanStatus().getStatus():null; //wdev-13495
			form.btnReactivate().setVisible(isCcoSpecific && (ims.nursing.vo.lookups.CarePlanStatus.DISCONTINUED.equals(cStatus)||ims.nursing.vo.lookups.CarePlanStatus.COMPLETE.equals(cStatus)));
		}
		form.bNoteCorrection().setEnabled(!isEditMode && form.gridNotes().getValue()!= null && form.gridNotes().getValue().getActiveIsNotNull() && form.gridNotes().getValue().getActive());
		form.lnkClinicalNote().setEnabled(!isEditMode);
		form.chkActive().setEnabled(!isEditMode);
		updateContextMenuActionsState();
		
		if(!isEditMode && form.getLocalContext().getCarePlanIsNotNull() && form.getGlobalContext().Core.getCurrentCareContextIsNotNull() && !form.getLocalContext().getCarePlan().getCareContext().equals(form.getGlobalContext().Core.getCurrentCareContext())) //WDEV-14521
		{
			showOnlyCreateDuplicateAndClose();
		}
		else
			form.btnCreateDuplicate().setVisible(false);
	}
	private void showOnlyCreateDuplicateAndClose() {
		form.bSave().setVisible(false);
		form.btnCancel().setVisible(false);
		form.bEval().setVisible(false);	
		form.bUpdate().setVisible(false);	
		form.bNoteCorrection().setVisible(false);
		form.bPrint().setVisible(false);
		form.btnReactivate().setVisible(false);
		form.btnReview().setVisible(false);
		form.lnkClinicalNote().setVisible(false);	
				
		form.bClose().setVisible(true);
		form.bClose().setEnabled(true);
	}

	private void updateContextMenuActionsState()
	{
		boolean editMode = FormMode.EDIT.equals(form.getMode());
		
		boolean isCcoSpecific =  ConfigFlag.GEN.CARE_PLAN_FUNCTIONALITY_TYPE.getValue().equals("CCO");
		boolean isRowSelected = form.dyngrdActions().getSelectedRow() != null;
		boolean isCurrentActionActive = false;
		if (isRowSelected)
			isCurrentActionActive = ((CarePlanInterventions)form.dyngrdActions().getValue()).getActive();
		
		boolean currentActionRemoved = false;
		if (isRowSelected)
			currentActionRemoved = Boolean.TRUE.equals(((CarePlanInterventions)form.dyngrdActions().getValue()).getIsRemoved());
			
		form.getContextMenus().Nursing.getCarePlanEvaluateActionADDItem().setVisible(editMode);
		form.getContextMenus().Nursing.getCarePlanEvaluateActionMARKACTIONCOMPLETEItem().setVisible(editMode && isRowSelected && isCcoSpecific && isCurrentActionActive && !currentActionRemoved);
		form.getContextMenus().Nursing.getCarePlanEvaluateActionREACTIVATEACTIONItem().setVisible(editMode && isRowSelected && isCcoSpecific && !isCurrentActionActive && engine.hasRight(AppRight.NURSING_ADMIN_ROLE) && !currentActionRemoved);
		
		form.getContextMenus().Nursing.getCarePlanEvaluateActionREMOVE_ACTIONItem().setVisible(editMode && isRowSelected && isCcoSpecific && !currentActionRemoved);
		form.getContextMenus().Nursing.getCarePlanEvaluateActionREINSTATE_ACTIONItem().setVisible(editMode && isRowSelected && isCcoSpecific && currentActionRemoved);
	}
	private void populateDynGridRowFromData(DynamicGridRow newRow, CarePlanInterventions inter)
	{
		boolean isCcoSpecific = ConfigFlag.GEN.CARE_PLAN_FUNCTIONALITY_TYPE.getValue().equals("CCO");
		boolean activeOnly = form.cbFilter().getValue().equals("0");
		boolean isRemovedOrReinstatedAction = isCcoSpecific && (Boolean.TRUE.equals(inter.getIsRemoved()) || Boolean.FALSE.equals(inter.getIsRemoved())); //WDEV-16795 
				
		
		DynamicGridColumn column = null;
		DynamicGridCell newCell = null;
		String addInfo = ""; //WDEV-16795
		String lineDelimiter = "<br/>"; 
		
		if (isRemovedOrReinstatedAction) //WDEV-16795 
		{
			addInfo = buildRemovedReinstatedActionTooltip (inter);
		}
		if (!isCcoSpecific)
		{
			column = form.dyngrdActions().getColumns().getByIdentifier(SELECTED_COLUMN_INDENTIFIER);
			newCell = newRow.getCells().newCell(column, DynamicCellType.BOOL);
			newCell.setValue(inter.getActive());
			newCell.setReadOnly(CarePlanInterventionManOpt.MANDATORY.equals(inter.getInterventionType()));
		}
		column = form.dyngrdActions().getColumns().getByIdentifier(ACTION_COLUMN_INDENTIFIER);
		newCell = newRow.getCells().newCell(column, DynamicCellType.STRING);
		newCell.setValue(inter.getDescription());
		newCell.setTooltip(inter.getDescription() != null ? inter.getDescription() + lineDelimiter + addInfo : addInfo);
		newCell.setReadOnly(true);
		
		column = form.dyngrdActions().getColumns().getByIdentifier(STARTD_COLUMN_INDENTIFIER);
		newCell = newRow.getCells().newCell(column, DynamicCellType.DATE);
		newCell.setValue(inter.getStartDate());
		newCell.setTooltip(inter.getStartDate() != null ? inter.getStartDate() + lineDelimiter +  addInfo : addInfo);
		newCell.setReadOnly(true);
		
		column = form.dyngrdActions().getColumns().getByIdentifier(STARTB_COLUMN_INDENTIFIER);
		newCell = newRow.getCells().newCell(column, DynamicCellType.STRING);
		newCell.setValue(inter.getStartByIsNotNull() ? inter.getStartBy().toString():null);
		newCell.setTooltip(inter.getStartByIsNotNull() ? inter.getStartBy().toString() + lineDelimiter + addInfo : addInfo ); //wdev-13285 //WDEV-16795 
		newCell.setReadOnly(true);
		
		if (!activeOnly)
		{
			column = form.dyngrdActions().getColumns().getByIdentifier(STOPD_COLUMN_INDENTIFIER);
			newCell = newRow.getCells().newCell(column, DynamicCellType.DATE);
			newCell.setValue(inter.getStopDate());
			newCell.setTooltip(inter.getStopDateIsNotNull() ? inter.getStopDate() + lineDelimiter + addInfo : addInfo);
			newCell.setReadOnly(true);
			
			column = form.dyngrdActions().getColumns().getByIdentifier(STOPB_COLUMN_INDENTIFIER);
			newCell = newRow.getCells().newCell(column, DynamicCellType.STRING);
			newCell.setValue(inter.getStopByIsNotNull()?inter.getStopBy().toString():null);
			newCell.setTooltip(inter.getStopByIsNotNull()  ?inter.getStopBy().toString() + lineDelimiter + addInfo :addInfo) ; //wdev-13285 //WDEV-16795 
			newCell.setReadOnly(true);
		}
		
		if (isCcoSpecific)
		{
			column = form.dyngrdActions().getColumns().getByIdentifier(NOTES_COLUMN_INDENTIFIER);
			newCell = newRow.getCells().newCell(column, DynamicCellType.STRING);
			newCell.setStringMaxLength(100);
			newCell.setValue(inter.getAdditionalInfo());
			newCell.setTooltip(inter.getAdditionalInfoIsNotNull() ? inter.getAdditionalInfo() + lineDelimiter  + addInfo : addInfo);	//wdev-13285 //WDEV-16795 
			newCell.setReadOnly(false);
		}
		
		if (isCcoSpecific && Boolean.TRUE.equals(inter.getIsRemoved()))
		{
			newRow.setTextColor(Color.Gray);
		}
		
		newRow.setValue(inter);
	}

	private boolean shouldAdd(CarePlanInterventions carePlanInterventions)
	{
		if (carePlanInterventions == null )
			return false;
		if (form.cbFilter().getValue().equals("0") && !(carePlanInterventions.getActiveIsNotNull() && carePlanInterventions.getActive() && !Boolean.TRUE.equals(carePlanInterventions.getIsRemoved())))
			return false;
		return true;
	}
	
	private String buildRemovedReinstatedActionTooltip(CarePlanInterventions action)
	{
		if (action == null)
			return null;
		StringBuilder tooltip = new StringBuilder();
		if (action.getRemovalAuthoringInformationIsNotNull() && Boolean.TRUE.equals(action.getIsRemoved()))
		{
			if (action.getRemovalAuthoringInformation().getAuthoringHcp() != null)
			{	
				tooltip.append("Removed By: <b>" + action.getRemovalAuthoringInformation().getAuthoringHcp().getIMosName() + "</b>");
			}
			if (action.getRemovalAuthoringInformation().getAuthoringDateTime() != null)
			{
				tooltip.append("<br/> Removal Date/Time: <b>" + action.getRemovalAuthoringInformation().getAuthoringDateTime() + "</b>");
			}
		}
		else if (action.getReinstatingAuthoringInformationIsNotNull() && Boolean.FALSE.equals(action.getIsRemoved()))
		{
			if (action.getReinstatingAuthoringInformation().getAuthoringHcp() != null)
			{	
				tooltip.append("Reinstated By: <b>" + action.getReinstatingAuthoringInformation().getAuthoringHcp().getIMosName() + "</b>");
			}
			if (action.getReinstatingAuthoringInformation().getAuthoringDateTime() != null)
			{
				tooltip.append("<br/> Reinstated Date/Time: <b>" + action.getReinstatingAuthoringInformation().getAuthoringDateTime() + "</b>");
			}
		}
		
		return  tooltip.toString();
		
	}
	private void initialize() 
	{
		if (form.getLocalContext().getFromReview() == null)
			form.getLocalContext().setFromReview(Boolean.FALSE);

		form.getLocalContext().setIsNewEvalNote(new Boolean(false));

		
		if (engine.getPreviousNonDialogFormName() != null)
			form.getLocalContext().setLastFormName(engine.getPreviousNonDialogFormName());

		if (form.getLocalContext().getLastFormName() != null && form.getLocalContext().getLastFormName().equals(form.getForms().Nursing.CarePlanReview))
		{
			form.btnReview().setVisible(true);
			form.btnReview().setEnabled(true);
			form.bClose().setVisible(false);
			form.bPrint().setVisible(false);
			form.getLocalContext().setFromReview(Boolean.TRUE);
		}
		else
		{
			form.bPrint().setEnabled(true);
			form.btnReview().setVisible(false);
			Discharge dischargeVO = domain.getDischarge(form.getGlobalContext().Core.getCurrentCareContext());
			if (dischargeVO != null)
			{
				if (dischargeVO.getDateTimeDischarged() != null)
					form.bUpdate().setEnabled(false);
			}
			else
			{
				form.bUpdate().setEnabled(true);
			}
		}
		
		if (ims.configuration.gen.ConfigFlag.UI.DISPLAY_CAREPLAN_NOTE_LINK.getValue())
		{
			form.lnkClinicalNote().setVisible(true);
		}
		else
		{
			form.lnkClinicalNote().setVisible(false);
		}
		
		form.cbFilter().clear();
		form.cbFilter().newRow("0", "Active Actions");
		form.cbFilter().newRow("1", "All Actions");
		
		boolean isCcoSpecific = ConfigFlag.GEN.CARE_PLAN_FUNCTIONALITY_TYPE.getValue().equals("CCO");
		form.cbFilter().setValue(isCcoSpecific ? "1" : "0");
		
		form.chkActive().setValue(true);
		
		form.dteNotesFrom().setValue(new Date().addDay(-30));
		form.dteNotesTo().setValue(new Date());
		
		form.chkActive().setVisible( ! isCcoSpecific);//wdev-13781
		
		initDynGrid();
		//------------
		//form.getGlobalContext().Nursing.setCarePlanInterventions(null);
		//------------
	}

	private void initDynGrid()
	{
		form.dyngrdActions().clear();
		boolean isCcoSpecific = ConfigFlag.GEN.CARE_PLAN_FUNCTIONALITY_TYPE.getValue().equals("CCO");
		
		boolean onlyActive = form.cbFilter().getValue().equals("0");
		
		DynamicGridColumnCollection columns = form.dyngrdActions().getColumns();
		DynamicGridColumn newColumn = null;
		if (!isCcoSpecific)
		{
			newColumn = columns.newColumn("Selected", SELECTED_COLUMN_INDENTIFIER);
			newColumn.setWidth(SELECTED_COLUMN_WIDTH);
		}
		newColumn = columns.newColumn("Care Plan Actions", ACTION_COLUMN_INDENTIFIER);
		newColumn.setWidth(ACTION_COLUMN_WIDTHS[isCcoSpecific?(onlyActive?2:3):(onlyActive?0:1)]);
		newColumn = columns.newColumn("Start Date",STARTD_COLUMN_INDENTIFIER);
		newColumn.setWidth(STARTD_COLUMN_WIDTH);
		newColumn = columns.newColumn("By",STARTB_COLUMN_INDENTIFIER);
		newColumn.setWidth(STARTB_COLUMN_WIDTH[isCcoSpecific || !onlyActive?1:0]);
		
		if (!onlyActive)
		{
			newColumn = columns.newColumn("Stop Date",STOPD_COLUMN_INDENTIFIER);
			newColumn.setWidth(STOPD_COLUMN_WIDTH);
			
			newColumn = columns.newColumn("By",STOPB_COLUMN_INDENTIFIER);
			newColumn.setWidth(STOPB_COLUMN_WIDTH[isCcoSpecific?1:0]);
			
		}
		
		if (isCcoSpecific)
		{
			newColumn = columns.newColumn("Additional Info", NOTES_COLUMN_INDENTIFIER);
			newColumn.setWidth(NOTES_COLUMN_WIDTH);
		}
		
	}

	

	private void populateNotesGrid(CarePlanRefVo carePlanRefVo)
	{
		form.gridNotes().getRows().clear();
		
		//validaion that dateFrom and dateTo are entered
		List<String> errors = new ArrayList<String>();
		
		if(form.dteNotesFrom().getValue() == null)
			errors.add("'Date From' is mandatory");
		if(form.dteNotesTo().getValue() == null)
			errors.add("'Date To' is mandatory");
		
		if(form.dteNotesFrom().getValue() != null && form.dteNotesTo().getValue() != null)
			if(form.dteNotesFrom().getValue().isGreaterThan(form.dteNotesTo().getValue()))
				errors.add("'Date To' cannot be before 'Date From'");
		
		if(errors.size() > 0)
		{
			engine.showErrors(errors.toArray(new String[0]));
			return;
		}
		
		if (carePlanRefVo != null)
		{
			populateEvaluationNotes(domain.listEvaluationNotesforCarePlanAndByDateRange(carePlanRefVo, form.dteNotesFrom().getValue(), form.dteNotesTo().getValue(), (ConfigFlag.GEN.CARE_PLAN_FUNCTIONALITY_TYPE.getValue().equals("CCO") ? false : form.chkActive().getValue())));
			populateClinicalNotes(domain.listClinicalNotesForCarePlanAndDateRange(carePlanRefVo, form.dteNotesFrom().getValue(), form.dteNotesTo().getValue(), (ConfigFlag.GEN.CARE_PLAN_FUNCTIONALITY_TYPE.getValue().equals("CCO") ? false : form.chkActive().getValue())));
			
			form.gridNotes().sort(0, SortOrder.DESCENDING);
		}
		
	}

	private void populateClinicalNotes(NursingClinicalNotesVoCollection clinNotesColl) 
	{
		GenForm.gridNotesRow row;
		if (clinNotesColl != null)
		{
			for (int i = 0; i < clinNotesColl.size(); i++)
			{
				ClinicalNotesVo clinNote = clinNotesColl.get(i);

				row = form.gridNotes().getRows().newRow();

				row.setcolNote(clinNote.getClinicalNote());
				if (clinNote.getAuthoringInfo() != null &&
						//WDEV-3852
						clinNote.getAuthoringInfo().getAuthoringHcp() != null)
							row.setcolBy(clinNote.getAuthoringInfo().getAuthoringHcp().getName().toString());
				row.setcolDateTime(clinNote.getRecordingDateTime());
				row.setcolNoteType(clinNote.getNoteTypeIsNotNull() ? clinNote.getNoteType().toString() : "Clinical");//wdev-13781
				row.setcolStatus(clinNote.getCurrentStatusIsNotNull() && clinNote.getCurrentStatus().getStatusIsNotNull() ? clinNote.getCurrentStatus().getStatus().toString() : "");//wdev-13781
				
				//WDEV-14553
				
				if (clinNote.getCurrentStatusIsNotNull() && clinNote.getCurrentStatus().getCorrectedByIsNotNull())
				{		
					StringBuffer noteToDisplay = new StringBuffer("");
					
					noteToDisplay.append(clinNote.getClinicalNote()+"\n");
					
					noteToDisplay.append("Corrected By: "+ clinNote.getCurrentStatus().getCorrectedBy().toString());
					
					if (clinNote.getCurrentStatus().getDateTimeIsNotNull())
					{
							noteToDisplay.append( " on " +clinNote.getCurrentStatus().getDateTime().getDate()+ " at " + clinNote.getCurrentStatus().getDateTime().getTime() );		
					}
					
					if (clinNote.getCurrentStatus().getCorrectionReasonIsNotNull())
					{
						noteToDisplay.append(" for the following reason: "+clinNote.getCurrentStatus().getCorrectionReason());
					}
					
					row.setcolNote(noteToDisplay.toString());
					
					//WDEV-15029	
					row.setTooltipForcolNote(noteToDisplay.toString());
					
				}
				else
				{
					row.setcolNote(clinNote.getClinicalNote());
					//WDEV-15029	
					row.setTooltipForcolNote(clinNote.getClinicalNote());
				}
				
				row.setSelectable(false);
			}
		}	
	}

	private void populateEvaluationNotes(CarePlanEvaluationNoteCollection coll) 
	{
		if (coll != null && coll.size() != 0)
		{
			GenForm.gridNotesRow row;

			for (int i = 0; i < coll.size(); i++)
			{
				CarePlanEvaluationNote note = coll.get(i);

				if (! ConfigFlag.GEN.CARE_PLAN_FUNCTIONALITY_TYPE.getValue().equals("CCO")
					&& form.chkActive().getValue() == Boolean.TRUE.booleanValue())
				{
					if (note.getActive().booleanValue() == false)
						continue;
				}

				row = form.gridNotes().getRows().newRow();
				row.setValue(note);

				if (note.getRecordedBy() != null)
					row.setcolBy(note.getRecordedBy().getName().toString());
				row.setcolDateTime(note.getRecordedDateTime());
				row.setcolNoteType("Evaluation");
				
				if (!note.getNoteIsNotNull()) //WDEV-14474
				{
					note.setNote("");
				}

				if (note.getActive().booleanValue() == false) // Correction
																// has been
																// added
				{
					String strCorrectedBy = "";

					if (note.getCorrectedBy() != null)
						strCorrectedBy = note.getCorrectedBy().toString();

					row.setcolNote(note.getNote() + "\nCorrected By:" + strCorrectedBy + " on " + note.getCorrectionDateTime().getDate() + " at " + note.getCorrectionDateTime().getTime() + " for the following reason: " + (note.getCorrectionReason()!=null? note.getCorrectionReason():""));//WDEV-14487
					
					//WDEV-15029	
					row.setTooltipForcolNote(note.getNote() + "\nCorrected By:" + strCorrectedBy + " on " + note.getCorrectionDateTime().getDate() + " at " + note.getCorrectionDateTime().getTime() + " for the following reason: " + (note.getCorrectionReason()!=null? note.getCorrectionReason():""));
					
					row.setSelectable(false);
				}
				else 
				{	
					row.setcolNote(note.getNote());
					//WDEV-15029
					row.setTooltipForcolNote(note.getNote());
				}
				
			}
		}
		
	}

	protected void onFormDialogClosed(ims.framework.FormName formName, ims.framework.enumerations.DialogResult result) throws ims.framework.exceptions.PresentationLogicException
	{
		if (formName.equals(form.getForms().Core.YesNoDialog) && result.equals(DialogResult.YES))
		{
			CarePlan cpDuplicate = createDuplicateCarePlan();

			if (cpDuplicate == null)
				return;

			String[] arrErrors = cpDuplicate.validate();
			if (arrErrors != null)
			{
				engine.showErrors("Validation Errors", arrErrors);
				return;
			}

			try
			{
				cpDuplicate = domain.saveCarePlan(cpDuplicate);
			}
			catch (StaleObjectException e)
			{
				engine.showMessage(ims.configuration.gen.ConfigFlag.UI.STALE_OBJECT_MESSAGE.getValue());
				open();
				return;
			}

			if (form.getLocalContext().getLastFormName() != null && form.getLocalContext().getLastFormName().equals(form.getForms().Nursing.CarePlanReview))
			{
				engine.open(form.getForms().Nursing.CarePlanReview);
			}
			
			onBCancelClick();		
			return;
		}
		
		if (result.equals(DialogResult.OK) && formName.equals(form.getForms().Core.Reports))
		{
			printReport();
		}
		else if (formName.equals(form.getForms().Nursing.CarePlanAddAction) && result.equals(DialogResult.OK))
		{
			// WDEV-13315
			// Refresh 'Additional info' tool tips (if needed as this column depends on a flag)
			boolean isCcoSpecific = ConfigFlag.GEN.CARE_PLAN_FUNCTIONALITY_TYPE.getValue().equals("CCO");
			
			if (isCcoSpecific)
			{
				refreshAdditionalInfoTooltips();
			}
			
			// Get from the global context any new actions required
			CarePlanTemplateInterventionCollection modColl = form.getGlobalContext().COE.getCarePlanTemplateInterventions();
			form.getGlobalContext().COE.setCarePlanTemplateInterventions(null);
			Object back = form.dyngrdActions().getValue();
			form.dyngrdActions().setValue(null);
			if (modColl != null)
			{
				
				for (int i = 0; i < modColl.size(); i++)
				{
					
					CarePlanTemplateIntervention tempInt = modColl.get(i);
					if (tempInt == null)
						continue;
					
					CarePlanInterventions inte = getInteventionFromTemplate(tempInt);
					populateDynGridRowFromData(form.dyngrdActions().getRows().newRow(),inte);
					if (!form.getLocalContext().getCarePlan().getInterventionsIsNotNull())
						form.getLocalContext().getCarePlan().setInterventions(new CarePlanInterventionsCollection());
					form.getLocalContext().getCarePlan().getInterventions().add(inte);
				}
			}			
			form.dyngrdActions().setValue(back);
			
		}
		else if (formName.equals(form.getForms().Nursing.CarePlanEvaluation))
		{
			if(result.equals(DialogResult.OK))
			{
				CarePlanEvaluationNote eval = form.getGlobalContext().COE.getCarePlanEvaluation();
				if (eval != null)
				{
					GenForm.gridNotesRow row = form.gridNotes().getRows().newRow();
					row.setcolDateTime(eval.getRecordedDateTime());
					row.setcolNoteType("Evaluation");

					if (eval.getRecordedBy() != null)
						row.setcolBy(eval.getRecordedBy().getName().toString());

					row.setcolNote(eval.getNote());
					row.setSelectable(false);

					row.setValue(eval);
					form.bEval().setEnabled(false);
					form.bSave().setVisible(true);
					form.btnCancel().setVisible(true);
					form.bClose().setVisible(false);

					form.bUpdate().setEnabled(true);


					
					form.getLocalContext().setIsNewEvalNote(new Boolean(true));
				}

				form.setMode(FormMode.VIEW);
				form.gridNotes().setEnabled(true);
				form.bUpdate().setEnabled(false);
				form.bEval().setEnabled(false);
				form.bSave().setVisible(true);
				form.btnCancel().setVisible(true);
				
			}
			initialize();
		
			open();
			
			form.bPrint().setEnabled(true);
		}
		else if (formName.equals(form.getForms().Nursing.CarePlanNoteCorrect) && result.equals(DialogResult.OK))
		{
			if(form.getGlobalContext().COE.getCarePlanEvaluationIsNotNull())
			{
				CarePlanEvaluationNote voNote = form.getGlobalContext().COE.getCarePlanEvaluation();
				voNote.setCarePlan(form.getLocalContext().getCarePlan());
				
				String[] arrErrors = voNote.validate();
				if(arrErrors != null)
				{
					engine.showErrors(arrErrors);
					return;
				}
				
				try
				{
					domain.saveEvaluationNote(voNote);
				}
				catch (StaleObjectException e)
				{
					engine.showMessage(ConfigFlag.UI.STALE_OBJECT_MESSAGE.getValue());
				}
			}
			
			form.setMode(FormMode.VIEW);
			form.gridNotes().setEnabled(true);
			form.bUpdate().setEnabled(false);
			form.bEval().setVisible(false);
			form.bSave().setVisible(true);
			form.btnCancel().setVisible(true);
			
			// save the care plan
			onBSaveClick();
		}
		else if (formName.equals(form.getForms().Nursing.CarePlanReviewDialog) && (form.getGlobalContext().Nursing.getShowCarePlanRvwDialog().equals(Boolean.TRUE)))
		{
			engine.open(form.getForms().Nursing.CarePlanReview);
		}
		else if (formName.equals(form.getForms().Nursing.ClinicalNoteDialog))
		{
			initialize();
			open();
		}

//		if (result.equals(DialogResult.CANCEL))
//		{
//			if (formName.equals(form.getForms().Nursing.CarePlanAddAction))
//			{
//				return;
//			}
//			form.setMode(FormMode.VIEW);
//			//form.gridNotes().setEnabled(true);
//			// 27/10/2004 - Sinead Request - If Cancel and coming from
//			// CarePlanAddAction then
//			// enable Evaluation and disable Evaluate
//			
//			form.bEval().setEnabled(false);
//			form.bUpdate().setEnabled(true);
//			
//			
//
//			if (form.getLocalContext().getLastFormName() != null && form.getLocalContext().getLastFormName().equals(form.getForms().Nursing.CarePlanReview))
//				form.btnReview().setVisible(true);
//			
//		}
		if (formName.equals(form.getForms().Nursing.CarePlanReviewDialog))
		{
			form.bUpdate().setEnabled(false);
		}
		if (formName.equals(form.getForms().Nursing.RptCarePlanDetails) && form.btnReviewHistory().isVisible())
		{
			form.bUpdate().setEnabled(false);
		}
		if (formName.equals(form.getForms().Nursing.CarePlanNoteCorrect) && result.equals(DialogResult.CANCEL) && form.btnReviewHistory().isVisible())
		{
			form.bUpdate().setEnabled(false);
		}
		updateControlState();

	}


	private CarePlanInterventions getInteventionFromTemplate(CarePlanTemplateIntervention template)
	{
		CarePlanInterventions result = new CarePlanInterventions();
		Object Object = domain.getHcpLiteUser();
		HcpLiteVo hcpLiteVo = Object!=null?(HcpLiteVo)Object:null;
		result.setDescription(template.getIntervention());
		result.setActive(new Boolean(true));

		
		result.setStartBy(hcpLiteVo);

		result.setInterventionType(template.getInterventionType());
		result.setOrder(form.getLocalContext().getCarePlan().getInterventions() == null ? 0:form.getLocalContext().getCarePlan().getInterventions().size());
		result.setStartDate(new Date());
		return result;
	}
	protected void loadCarePlanFromScreen()
	{

		CarePlan cp;
		if ((cp = form.getLocalContext().getCarePlan()) == null)
			cp = new CarePlan();

		cp.setTitle(form.textTitle().getValue());
		cp.setObjective(form.textObjective().getValue());


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

		
		boolean isCcoSpecific = ConfigFlag.GEN.CARE_PLAN_FUNCTIONALITY_TYPE.getValue().equals("CCO");
		//If it is the default behavior update the status
		
			DynamicGridColumn col = form.dyngrdActions().getColumns().getByIdentifier(SELECTED_COLUMN_INDENTIFIER);
			DynamicGridColumn colNotes = form.dyngrdActions().getColumns().getByIdentifier(NOTES_COLUMN_INDENTIFIER);
			for (int i = 0 ;i < form.dyngrdActions().getRows().size(); i++)
			{
				CarePlanInterventions value = (CarePlanInterventions)form.dyngrdActions().getRows().get(i).getValue();
				if (isCcoSpecific)
				{
					value.setAdditionalInfo((String) form.dyngrdActions().getRows().get(i).getCells().get(colNotes).getValue());
				}
				else
				{
    				if (!Boolean.TRUE.equals(form.dyngrdActions().getRows().get(i).getCells().get(col).getValue()))
    				{
    					value.setActive(false);
    					value.setStopBy(hcpLiteVo);
    					value.setStopDate(new Date());
    				}
				}
			}
		
		

		// Evaluation Notes Grid
		GenForm.gridNotesRowCollection notesRows = form.gridNotes().getRows();
		CarePlanEvaluationNoteCollection notesColl = new CarePlanEvaluationNoteCollection();// cp.getInterventions();

		CarePlanEvaluationNote note;
		for (int i = 0; i < notesRows.size(); i++)
		{
			note = notesRows.get(i).getValue();
			if (note != null)
				notesColl.add(note);
		}


		CarePlanEvaluationNote lastNonCorrectednote = null;
		if (notesColl.size() > 0)
		{
			lastNonCorrectednote = notesColl.get(0);
			for (int x = 1; x < notesColl.size(); x++)
			{
				// Loop through the notesColl Collection to find the last
				// Evaluation record that is not corrected
				// (Corrected records are appended on the end in the loop above)
				if (notesColl.get(x).getCorrectionDateTime() != null) // Corrrected
																		// record
					break;

				lastNonCorrectednote = notesColl.get(x);
			}

			if (lastNonCorrectednote != null)
			{
				if (lastNonCorrectednote.getNextEvaluationDate() != null)
					cp.setNextEvaluationDate(lastNonCorrectednote.getNextEvaluationDate());
			}
		}

		if (form.getLocalContext().getLastFormName() != null && form.getLocalContext().getLastFormName().equals(form.getForms().Nursing.CarePlanReview))
		{
			CarePlanReviewHistoryCollection reviewColl = new CarePlanReviewHistoryCollection();

			reviewColl = cp.getCarePlanReviews();

			MemberOfStaffShortVo memStaffShortVo = (MemberOfStaffShortVo) domain.getMosUser();

			CarePlanReviewHistory review = null;
			review = new CarePlanReviewHistory();

			HcpLiteVo hcpLite = null;
			if (memStaffShortVo != null && memStaffShortVo.getHcp() != null)
			{	
				
				hcpLite = new HcpLiteVo(); 
				
			hcpLite.setHcpType(memStaffShortVo.getHcp().getHcpType());
			hcpLite.setID_Hcp(memStaffShortVo.getHcp().getID_Hcp());
			hcpLite.setMos(memStaffShortVo.getHcp().getMos());
			}	
			
			if(hcpLite != null)
			review.setReviewBy(hcpLite);

			review.setReviewDateTime(new DateTime());

			reviewColl.add(review);

			cp.setCarePlanReviews(reviewColl);

			if (memStaffShortVo != null && memStaffShortVo.getHcp() != null)
				cp.setLastReviewedBy(memStaffShortVo.getHcp());

			cp.setLastReviewedDate(new DateTime());
		}
		CarePlanStatus status = null;
		if (form.getGlobalContext().COE.getCarePlan() != null)
			status = form.getGlobalContext().COE.getCarePlan().getCurrentCarePlanStatus();

		if (status != null)
		{
			if (form.getLocalContext().getCarePlanStatus() != null)
			{
				if (!status.getStatus().equals(form.getLocalContext().getCarePlanStatus()))
				{
					cp.setCurrentCarePlanStatus(status);
					CarePlanStatusCollection voColl = cp.getCarePlanStatus();
					voColl.add(status);
					cp.setCarePlanStatus(voColl);
				}
			}
		}
		//if(flag == false)
		form.getLocalContext().setCarePlan(cp);
		//else
			//form.getGlobalContext().Nursing.setCarePlanInterventions(interventionColl);
	}
	
	protected void onBPrintClick()
	{
		//engine.open(form.getForms().Nursing.RptCarePlanDetails);
		engine.open(form.getForms().Core.Reports);
	}

	protected void onBSaveClick() throws ims.framework.exceptions.PresentationLogicException
	{
		loadCarePlanFromScreen();
		CarePlan cp = form.getLocalContext().getCarePlan();

		if (cp == null)
			return;

		String[] arrErrors = cp.validate();
		if (arrErrors != null)
		{
			engine.showErrors("Validation Errors", arrErrors);
			return;
		}

		try
		{
			cp = domain.saveCarePlan(cp);
		}
		catch (StaleObjectException e)
		{
			engine.showMessage(ims.configuration.gen.ConfigFlag.UI.STALE_OBJECT_MESSAGE.getValue());
			open();
			return;
		}

		if (form.getLocalContext().getLastFormName() != null && form.getLocalContext().getLastFormName().equals(form.getForms().Nursing.CarePlanReview))
		{
			engine.open(form.getForms().Nursing.CarePlanReview);
		}

		form.bEval().setVisible(true);
		form.bUpdate().setEnabled(true);
		form.bPrint().setEnabled(true);

		open();
	}

	protected void onCbFilterValueChanged() throws ims.framework.exceptions.PresentationLogicException
	{
		if (form.cbFilter().getValue() == null)
		{
			boolean isCcoSpecific = ConfigFlag.GEN.CARE_PLAN_FUNCTIONALITY_TYPE.getValue().equals("CCO");
			form.cbFilter().setValue(isCcoSpecific ? "1" : "0");
		}
		if (FormMode.EDIT.equals(form.getMode()))
				loadCarePlanFromScreen();
		initDynGrid();
		populateDynGrid(form.getLocalContext().getCarePlan().getInterventions());
		updateControlState();
	}

	protected void onImbAddClick()
	{
		newCarePlanAction();
	}

	private void newCarePlanAction()
	{
		// Pass in the Collection of unused careplan template actions
		CarePlanTemplateInterventionCollection coll = null;
		CarePlanTemplate voCPT = new CarePlanTemplate();
		if (form.getLocalContext().getCarePlan().getTemplate() != null)
		{
			voCPT.setID_CarePlanTemplate(form.getLocalContext().getCarePlan().getTemplate().getID_CarePlanTemplate());
			coll = domain.getCarePlanTemplateActions(voCPT);

			// Loop through the collection, removing those already specified on
			// the grid
			// Can only check on description??
			if (coll != null )
			{
				CarePlanTemplateInterventionCollection newColl = new CarePlanTemplateInterventionCollection();
				int p = 0;
				
				for (int i = 0; i < coll.size(); i++)
				{
					boolean rowFound = false;
					CarePlanTemplateIntervention interv = coll.get(i);
					for (int j = 0; form.getLocalContext().getCarePlan().getInterventionsIsNotNull() && j < form.getLocalContext().getCarePlan().getInterventions().size(); j++)
					{
						if (form.getLocalContext().getCarePlan().getInterventions().get(j).getDescription().equals(interv.getIntervention()))
						{
							rowFound = true;
							break;
						}
					}
					if (!rowFound)
					{
						newColl.add(interv);
						p++;
					}
				}
				form.getGlobalContext().COE.setCarePlanTemplateInterventions(newColl);
			}
		}
		engine.open(form.getForms().Nursing.CarePlanAddAction);
	}

	protected void onBUpdateClick() throws ims.framework.exceptions.PresentationLogicException
	{
		//WDEV-15031
		Object hcpUser = domain.getHcpLiteUser();
		if (hcpUser ==null)
		{
			engine.showMessage("User must be of type HCP.");
			return ;
		}
		
		form.setMode(FormMode.EDIT);
		boolean isCcoSpecific = ConfigFlag.GEN.CARE_PLAN_FUNCTIONALITY_TYPE.getValue().equals("CCO");
		form.cbFilter().setValue(isCcoSpecific ? "1" : "0");
		onCbFilterValueChanged();
		form.bSave().setVisible(false);
		form.btnCancel().setVisible(true);
		form.bClose().setVisible(false);
		form.bUpdate().setEnabled(false);
		form.bEval().setVisible(true);
		form.bEval().setEnabled(true);
		form.gridNotes().setEnabled(false);
		form.bPrint().setEnabled(false);

		

		if (form.getLocalContext().getLastFormName() != null && form.getLocalContext().getLastFormName().equals(form.getForms().Nursing.CarePlanReview))
			form.btnReview().setVisible(false);
		
		updateControlState();
	}

	protected void onBEvalClick() throws ims.framework.exceptions.PresentationLogicException
	{
		//WDEV-15031
		Object hcpUser = domain.getHcpLiteUser();
		if (hcpUser ==null)
		{
			engine.showMessage("User must be of type HCP.");
			return ;
		}
		
		//----------------------------
		loadCarePlanFromScreen();
		//----------------------------
		engine.open(form.getForms().Nursing.CarePlanEvaluation);
	}

	protected void onBCancelClick() throws ims.framework.exceptions.PresentationLogicException
	{
		form.setMode(FormMode.VIEW);
		if (form.getLocalContext().getFromReviewIsNotNull() && form.getLocalContext().getFromReview().booleanValue() == true) //wdev-13495
			engine.open(form.getForms().Nursing.CarePlanReview);
		else
			engine.open(form.getForms().Nursing.CarePlanOverview);

		form.bPrint().setEnabled(true);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see ims.coe.forms.careplandetails.Handlers#onGridNotesSelChange()
	 */
	protected void onGridNotesSelChange() throws PresentationLogicException
	{
		CarePlanEvaluationNote eval;
		if ((eval = form.gridNotes().getValue()) != null)
		{
			form.getGlobalContext().COE.setCarePlanEvaluation(eval);
	
			
		}
		updateControlState();

	}

	protected void onBNoteCorrectionClick() throws PresentationLogicException
	{
		//WDEV-15031
		Object hcpUser = domain.getHcpLiteUser();
		if (hcpUser ==null)
		{
			engine.showMessage("User must be of type HCP.");
			return ;
		}
		
		engine.open(form.getForms().Nursing.CarePlanNoteCorrect);
	}

	protected void onBtnReviewClick() throws PresentationLogicException
	{
		form.getGlobalContext().Nursing.setShowCarePlanRvwDialog(Boolean.TRUE);
		if (form.getLocalContext().getLastFormName() != null && form.getLocalContext().getLastFormName().equals(form.getForms().Nursing.CarePlanReview))
		{
			engine.open(form.getForms().Nursing.CarePlanReviewDialog);
		}
	}

	protected void onLnkClinicalNoteClick() throws PresentationLogicException
	{
		//engine.open(form.getForms().Nursing.ClinicalNoteDialog);
		//WDEV-15031
		Object hcpUser = domain.getHcpLiteUser();
		if (hcpUser ==null)
		{
			engine.showMessage("User must be of type HCP.");
			return ;
		}
		
		engine.open(form.getForms().Nursing.ClinicalNotesCarePlanDetails);
	}

	protected void onChkActiveValueChanged() throws PresentationLogicException
	{
		populateNotesGrid(form.getLocalContext().getCarePlan());
		updateControlState();
	}

	protected void onBtnCancelClick() throws PresentationLogicException
	{
		engine.open(form.getForms().Nursing.CarePlanOverview);
	}

	protected void onBtnReviewHistoryClick() throws PresentationLogicException
	{
		form.getGlobalContext().Nursing.setShowCarePlanRvwDialog(Boolean.FALSE);
		engine.open(form.getForms().Nursing.CarePlanReviewDialog);
	}

	protected void onContextMenuItemClick(int menuItemID, Control sender) throws PresentationLogicException
	{
		
		switch (menuItemID)
		{
			case GenForm.ContextMenus.NursingNamespace.CarePlanEvaluateAction.ADD:
				newCarePlanAction();
				break;
			case GenForm.ContextMenus.NursingNamespace.CarePlanEvaluateAction.EDITADTIONALNOTE:
				
				break;
			case GenForm.ContextMenus.NursingNamespace.CarePlanEvaluateAction.MARKACTIONCOMPLETE:
				loadCarePlanFromScreen();
				CarePlanInterventions value = (CarePlanInterventions)form.dyngrdActions().getSelectedRow().getValue();
				value.setStopBy((HcpLiteVo) domain.getHcpLiteUser());
				value.setStopDate(new Date());
				value.setActive(false);
				
				populateDynGrid(form.getLocalContext().getCarePlan().getInterventions());
				
				break;
			case GenForm.ContextMenus.NursingNamespace.CarePlanEvaluateAction.REACTIVATEACTION:
				loadCarePlanFromScreen();
				value = (CarePlanInterventions)form.dyngrdActions().getSelectedRow().getValue();
				value.setActive(true);
				value.setStopBy(null);
				value.setStopDate(null);
				populateDynGrid(form.getLocalContext().getCarePlan().getInterventions());
					
				
				break;
				
			case GenForm.ContextMenus.NursingNamespace.CarePlanEvaluateAction.REMOVE_ACTION:
				form.getLocalContext().setMessageBoxClosed(REMOVE_ACTION_MESSAGEBOX);
				engine.showMessage("Remove Action?", "Confirmation", MessageButtons.YESNO, MessageIcon.QUESTION);
				break;
				
			case GenForm.ContextMenus.NursingNamespace.CarePlanEvaluateAction.REINSTATE_ACTION:
				form.getLocalContext().setMessageBoxClosed(REINSTATE_ACTION_MESSAGEBOX);
				engine.showMessage("Re-Instate Action?", "Confirmation", MessageButtons.YESNO, MessageIcon.QUESTION);
				break;
				
			default:
				break;
		}
	updateControlState();
	}

	private void printReport()
	{
		String urlQueryServer = ConfigFlag.GEN.QUERY_SERVER_URL.getValue();
		String urlReportServer =ConfigFlag.GEN.REPORT_SERVER_URL.getValue();

		String[] obj = null;
		try
		{
			obj = domain.getReportAndTemplate(form.getGlobalContext().Core.getReportID(), form.getGlobalContext().Core.getTemplateID());
		}
		catch (DomainInterfaceException e)
		{
			engine.showMessage("Error retrieving report template !\r\n" + e.getMessage());
			return;
		}

		if (obj == null || obj.length == 0)
		{
			engine.showMessage("I could not get the report and template !");
			return;
		}

		QueryBuilderClient client = new QueryBuilderClient(urlQueryServer, engine.getSessionId());

		client.addSeed(new SeedValue("CarePlan_id", form.getLocalContext().getCarePlan().getID_CarePlan(), 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 onBtnViewNotesClick() throws PresentationLogicException 
	{
		populateNotesGrid(form.getLocalContext().getCarePlan());
		updateControlState();
	}

	@Override
	protected void onDyngrdActionsRowSelectionChanged(DynamicGridRow row) throws PresentationLogicException
	{
		updateControlState();
		
	}

	@Override
	protected void onDyngrdActionsRowSelectionCleared() throws PresentationLogicException
	{
		updateControlState();
		
	}

	@Override
	protected void onBtnReactivateClick() throws PresentationLogicException
	{
		
		doReactivate();
		onBSaveClick();
	}

	private void doReactivate()
	{
		CarePlanStatus status = new CarePlanStatus();
		status.setDateTime(new DateTime());
		status.setHCP((HcpLiteVo) domain.getHcpLiteUser());
		status.setStatus(ims.nursing.vo.lookups.CarePlanStatus.ACTIVE);
		form.getLocalContext().getCarePlan().setCurrentCarePlanStatus(status);
		form.getLocalContext().getCarePlan().getCarePlanStatus().add(status);
	}

	@Override
	protected void onBtnCreateDuplicateClick() throws PresentationLogicException {
				
		String msg = "Are you sure you want to create a duplicate?";

		form.getGlobalContext().Core.setYesNoDialogMessage(msg);
		engine.open(form.getForms().Core.YesNoDialog);
		
	}

	private CarePlan createDuplicateCarePlan() {
		CarePlan cpDuplicate = new CarePlan();
		CarePlan cp = form.getLocalContext().getCarePlan();
		
		cpDuplicate.setCareContext(form.getGlobalContext().Core.getCurrentCareContext());
		cpDuplicate.setClinicalContact(form.getGlobalContext().Core.getCurrentClinicalContact());
		cpDuplicate.setTitle(cp.getTitle());
		cpDuplicate.setObjective(cp.getObjective());
		cpDuplicate.setNextEvaluationDate(new Date());
		CarePlanInterventionsCollection collCarePlanInterventions = new CarePlanInterventionsCollection();
		if(cp.getInterventions()!=null)
		for(int i=0; i<cp.getInterventions().size(); i++){
			CarePlanInterventions action = cp.getInterventions().get(i);
			CarePlanInterventions carePlanIntervention = new CarePlanInterventions();
			carePlanIntervention.setDescription(action.getDescription());
			carePlanIntervention.setActive(true);
			carePlanIntervention.setStartDate(action.getStartDate());
			carePlanIntervention.setStartBy(action.getStartBy());

			carePlanIntervention.setOrder(action.getOrder());
			carePlanIntervention.setInterventionType(action.getInterventionType());
			carePlanIntervention.setFrequency(action.getFrequency());
			
			collCarePlanInterventions.add(carePlanIntervention);
		}
		cpDuplicate.setInterventions(collCarePlanInterventions);
		
		//Care Plan Status
		CarePlanStatus status = new CarePlanStatus();
		status.setDateTime(new DateTime());

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

		status.setHCP(hcpLiteVo);

		status.setStatus(ims.nursing.vo.lookups.CarePlanStatus.ACTIVE);

		cpDuplicate.setCurrentCarePlanStatus(status);

		CarePlanStatusCollection voColl = new CarePlanStatusCollection();
		voColl.add(status);
		cpDuplicate.setCarePlanStatus(voColl);

		return cpDuplicate;
	}

	/**
	 * WDEV-13315
	 * Function used to update 'Additional Info' cells tooltip
	 * 
	 * - will attempt to retrieve 'Additional Info' column - if this fails and the column is not found then function will terminate
	 * - will iterate all rows, and update tooltip for cells in 'Additional Info'
	 */
	private void refreshAdditionalInfoTooltips()
	{
		// Get 'Additional Info' column
		DynamicGridColumn additionalInfoColumn = form.dyngrdActions().getColumns().getByIdentifier(NOTES_COLUMN_INDENTIFIER);
		
		// If the 'Additional Info' column could not be retrieved then
		// exit the function
		if (additionalInfoColumn == null)
			return;
		
		// Iterate dynamic grid rows and update cells tooltip
		for (int i = 0; i < form.dyngrdActions().getRows().size(); i++)
		{
			// Row reference to grid row
			DynamicGridRow row = form.dyngrdActions().getRows().get(i);
			// Get the cell for 'Additional Info' cell
			DynamicGridCell cell = row.getCells().get(additionalInfoColumn);
			
			// Skip rows where a cell could not be retrieved
			if (cell == null)
				continue;
			
			// Set cell tooltip
			cell.setTooltip((String) cell.getValue());
		}
	}

	//WDEV-15252
	@Override
	protected void onLnkReturnToCarePlanWorklistClick() throws PresentationLogicException
	{
		engine.open(form.getForms().Nursing.CarePlanWorklist);
		
	}
}
