/FileExtraction/Java_unseen/IMS-MAXIMS_openMAXIMS/Source Library/openmaxims_workspace/Pathways/src/ims/pathways/forms/patientpathwaysawaitingvalidationworklist/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 Mara Iroaie using IMS Development Environment (version 1.80 build 5256.13787)
// Copyright (C) 1995-2014 IMS MAXIMS. All rights reserved.

package ims.pathways.forms.patientpathwaysawaitingvalidationworklist;

import ims.RefMan.vo.CatsReferralListVo;
import ims.configuration.ConfigFlag;
import ims.core.resource.people.vo.HcpRefVo;
import ims.core.vo.PatientShort;
import ims.core.vo.ServiceShortVo;
import ims.core.vo.ServiceShortVoCollection;
import ims.core.vo.lookups.PatIdType;
import ims.domain.exceptions.DomainInterfaceException;
import ims.domain.exceptions.StaleObjectException;
import ims.framework.FormName;
import ims.framework.MessageButtons;
import ims.framework.MessageIcon;
import ims.framework.delegates.CancelArgs;
import ims.framework.enumerations.DialogResult;
import ims.framework.enumerations.SortOrder;
import ims.framework.exceptions.PresentationLogicException;
import ims.framework.utils.Date;
import ims.pathways.forms.patientpathwaysawaitingvalidationworklist.GenForm.grdResultsRow;
import ims.pathways.vo.PathwayRTTStatusVo;
import ims.pathways.vo.PatientPathwaysAwaitingValidationSearchCriteriaVo;
import ims.pathways.vo.PatientPathwaysAwaitingValidationWorklistVo;
import ims.pathways.vo.PatientPathwaysAwaitingValidationWorklistVoCollection;

import java.util.ArrayList;
import java.util.Comparator;
//import ims.RefMan.forms.referralstatuslist.GenForm.Group1Enumeration;

public class Logic extends BaseLogic
{
	private static final long serialVersionUID = 1L;
	
	private static final int COLUMN_PATIENTNAME				= 1;
	private static final int COLUMN_RESP_CONSULTANT			= 9;
	
	private static final Integer VIEW_PATHWAY_FROM_VALIDATION_WORKLIST = new Integer(0);
	private static final Integer VIEW_RTTMANAGEMENT_FROM_VALIDATION_WORKLIST = new Integer(1); //WDEV-21155
	private static final Integer VIEW_REFERRAL_DETAILS_FROM_VALIDATION_WORKLIST = new Integer(3); //WDEV-21389
	
	private static Boolean ContextMenu_View_Pathway_Selected = new Boolean(false);

	@Override
	protected void onFormOpen(Object[] args) throws ims.framework.exceptions.PresentationLogicException
	{
		initialize();
		open();
	}
	
	private void open()
	{
		if (form.getGlobalContext().Pathways.getPatientPathwaysAwaitingValidationSearchCriteriaIsNotNull())
		{
			//WDEV-21431 	If the saved search criteria is for List pathways by RTT date, etc (checkbox search), ensure that the user's services
			// 				are NOT in the search criteria and that the Services label is blank
			/* WDEV-22258 if (Boolean.TRUE.equals(form.getGlobalContext().Pathways.getPatientPathwaysAwaitingValidationSearchCriteria().getRttIncluded()))
			{
				if (form.getGlobalContext().RefMan.getReferralServiceSearchList() != null)
				{
					form.getGlobalContext().RefMan.setReferralServiceSearchList(null);
					form.qmbService().setValue(null);
					form.lblServices().setValue(null);
				}
			} WDEV-22258  */
			//WDEV-21431
			setSearchCriteria(form.getGlobalContext().Pathways.getPatientPathwaysAwaitingValidationSearchCriteria());
			if (search(Boolean.FALSE))//WDEV-22441
				form.getGlobalContext().Pathways.setPatientPathwaysAwaitingValidationSearchCriteria(getSearchCriteria());
		}
		updateControlState();
	}

	private void setSearchCriteria(PatientPathwaysAwaitingValidationSearchCriteriaVo patientPathwaysAwaitingValidationSearchCriteria)
	{
		form.dteStartDate().setValue(patientPathwaysAwaitingValidationSearchCriteria.getStartDate());
		form.dteEndDate().setValue(patientPathwaysAwaitingValidationSearchCriteria.getEndDate());	
		form.chkInclude().setValue(Boolean.TRUE.equals(patientPathwaysAwaitingValidationSearchCriteria.getRttIncluded()) ? true : false);
		form.intRTTWeeks().setValue(patientPathwaysAwaitingValidationSearchCriteria.getNoOfWeeks());
		form.intNotValidated().setValue(patientPathwaysAwaitingValidationSearchCriteria.getNotValidatedNoOfWeeks());
	}

	private void initialize()
	{
		PatIdType dispIdType = PatIdType.getNegativeInstance(ConfigFlag.UI.DISPLAY_PATID_TYPE.getValue());
		form.grdResults().setcolNHSCaption(dispIdType.getText());
		form.dteStartDate().setValue(new Date());
		form.dteEndDate().setValue(new Date().addDay(7));
		ContextMenu_View_Pathway_Selected = Boolean.FALSE; //WDEV-21431
		
		//WDEV-21431
		intializeServices();
	}

	
	//WDEV-21431
	private void intializeServices()
	{
		Object hcp = domain.getHcpUser();
		if(hcp instanceof HcpRefVo)
		{
			prepareServiceSearchCriteria((HcpRefVo) hcp);
		}
	}

	//WDEV-21431
	private void prepareServiceSearchCriteria(HcpRefVo hcp)
	{
		if (form.getGlobalContext() != null
				&& form.getGlobalContext().Pathways != null
				&& form.getGlobalContext().Pathways.getPatientPathwaysAwaitingValidationSearchCriteria() != null
				&& form.getGlobalContext().Pathways.getPatientPathwaysAwaitingValidationSearchCriteria().getServices() != null)
		{
			form.getGlobalContext().RefMan.setReferralServiceSearchList(form.getGlobalContext().Pathways.getPatientPathwaysAwaitingValidationSearchCriteria().getServices());
		}
		else 
		if (form.getGlobalContext() != null
			&& form.getGlobalContext().Pathways != null
			&& form.getGlobalContext().Pathways.getPatientPathwaysAwaitingValidationSearchCriteria() != null
			&& form.getGlobalContext().Pathways.getPatientPathwaysAwaitingValidationSearchCriteria().getService() != null)
		{
			form.getGlobalContext().RefMan.setReferralServiceSearchList(new ServiceShortVoCollection());
			form.getGlobalContext().RefMan.getReferralServiceSearchList().add(form.getGlobalContext().Pathways.getPatientPathwaysAwaitingValidationSearchCriteria().getService());
		} 
		else
		{
			form.getGlobalContext().RefMan.setReferralServiceSearchList(domain.listServicesForLoggedHCP((HcpRefVo) hcp));
		}

		setServiceLabelValue(listServices());
	
		ServiceShortVoCollection referralServiceSearchList = form.getGlobalContext().RefMan.getReferralServiceSearchList();
		
		if(referralServiceSearchList != null && referralServiceSearchList.size() == 1)
		{
			form.qmbService().newRow(referralServiceSearchList.get(0), referralServiceSearchList.get(0).getServiceName() != null ? referralServiceSearchList.get(0).getServiceName() : "");
			form.qmbService().setValue(referralServiceSearchList.get(0));
			setServiceLabelValue(null);
		}
		else
		{
			form.qmbService().setValue(null);
		}

	}

	@Override
	protected void onGrdResultsSelectionChanged()
	{
		if (form.grdResults().getValue() != null && form.grdResults().getValue().getPatient() != null)
		{
			form.getGlobalContext().Core.setPatientShort(new PatientShort(form.grdResults().getValue().getPatient().getID_Patient(), form.grdResults().getValue().getPatient().getVersion_Patient()));
			form.getGlobalContext().Pathways.setSelectedPatientPathwayJourney(form.grdResults().getValue());
			form.getGlobalContext().Pathways.setSelectedPathway(form.grdResults().getValue() != null ? form.grdResults().getValue().getPathway() : null);
			//WDEV-21155
			form.getGlobalContext().Pathways.setPatientPathwaysAwaitingValidationWorklistVo(form.grdResults().getValue());
		}
		
		form.getLocalContext().setlcSelectedPathway(form.grdResults().getValue());
		updateControlState();
	}
	
	@Override
	protected void onImbClearClick() throws ims.framework.exceptions.PresentationLogicException
	{
		clearSearchCriteriaAndResults();
		clearContextVariables();
		form.getGlobalContext().Pathways.setPatientPathwaysAwaitingValidationSearchCriteria(null);
		form.getGlobalContext().RefMan.setReferralStatusListFilter(null); //WDEV-21431
		form.getGlobalContext().RefMan.setReferralServiceSearchList(null); //WDEV-21431

		updateControlState();
	}
	
	private void clearContextVariables()
	{
		form.getGlobalContext().Core.setPatientShort(null);
		form.getLocalContext().setlcSelectedPathway(null);
	}
	
	private void updateControlState()
	{
		form.getContextMenus().Pathways.getPathwaysAwaitingValidationVIEWItem().setVisible(form.grdResults().getValue() != null);
		form.getContextMenus().Pathways.getPathwaysAwaitingValidationVALIDATION_COMPLETEItem().setVisible(form.grdResults().getValue() != null); //WDEV-21155
		form.getContextMenus().Pathways.getPathwaysAwaitingValidationVIEWREFERRALDETAILSItem().setVisible(form.grdResults().getValue() != null); //WDEV-21389
		
		form.dteEndDate().setEnabled(!Boolean.TRUE.equals(form.chkInclude().getValue()));		
		form.dteStartDate().setEnabled(!Boolean.TRUE.equals(form.chkInclude().getValue()));
		
		form.intRTTWeeks().setEnabled(Boolean.TRUE.equals(form.chkInclude().getValue()));
		form.intRTTWeeks().setRequired(Boolean.TRUE.equals(form.chkInclude().getValue()));
		
		form.intNotValidated().setEnabled(Boolean.TRUE.equals(form.chkInclude().getValue()));
		form.intNotValidated().setRequired(Boolean.TRUE.equals(form.chkInclude().getValue()));
		
		//form.qmbService().setEnabled(!Boolean.TRUE.equals(form.chkInclude().getValue())); //WDEV-21431
		//form.imbServiceSearch().setEnabled(!Boolean.TRUE.equals(form.chkInclude().getValue())); //WDEV-21431
	}

	private void clearSearchCriteriaAndResults()
	{
		form.dteStartDate().setValue(null);
		form.dteEndDate().setValue(null);
		form.chkInclude().setValue(false);
		form.intRTTWeeks().setValue(null);
		form.intNotValidated().setValue(null);
		form.qmbService().setValue(null); //WDEV-21431
		form.lblServices().setValue(null); //WDEV-21431
		form.grdResults().getRows().clear();
	}

	@Override
	protected void onImbSearchClick() throws ims.framework.exceptions.PresentationLogicException
	{
		if (search(Boolean.TRUE))//WDEV-22441
			form.getGlobalContext().Pathways.setPatientPathwaysAwaitingValidationSearchCriteria(getSearchCriteria());
		updateControlState();
	}
	
	private PatientPathwaysAwaitingValidationSearchCriteriaVo getSearchCriteria()
	{
		PatientPathwaysAwaitingValidationSearchCriteriaVo searchCriteria = new PatientPathwaysAwaitingValidationSearchCriteriaVo();
		
		searchCriteria.setStartDate(form.dteStartDate().getValue());
		searchCriteria.setEndDate(form.dteEndDate().getValue());
		searchCriteria.setRttIncluded(Boolean.TRUE.equals(form.chkInclude().getValue()) ? true : false);
		searchCriteria.setNoOfWeeks(form.intRTTWeeks().getValue());
		searchCriteria.setNotValidatedNoOfWeeks(form.intNotValidated().getValue());
		searchCriteria.setService(form.qmbService().getValue()); //WDEV-21431
		searchCriteria.setServices(form.getGlobalContext().RefMan.getReferralServiceSearchList()); //WDEV-21431
		
		return searchCriteria;
	}

	private boolean search(Boolean isFromButton)
	{
		clearContextVariables();

		if (isSearchCriteriaValid())
		{
			 PatientPathwaysAwaitingValidationWorklistVoCollection results = domain.getPathways(getSearchCriteria());
			
			if (results == null || results.size() == 0)
			{
				if(isFromButton)//WDEV-22441
					engine.showMessage("No records matching your search criteria were found!", "No results",MessageButtons.OK, MessageIcon.INFORMATION);
				clearContextVariables();
				form.grdResults().getRows().clear();
				return true;
			}
				
			populateScreenFromData(results);
			
			return true;
		}
		
		return false;
	}

	private void populateScreenFromData(PatientPathwaysAwaitingValidationWorklistVoCollection results)
	{
		form.grdResults().getRows().clear();
		
		for(int i = 0; i< results.size(); i++)
		{
			if (results.get(i) == null)
				continue;
			
			addNewPathwayRow(results.get(i));	
		}	
		
		form.grdResults().setValue(form.getLocalContext().getlcSelectedPathway());
		
		if (form.grdResults().getValue() == null)
			form.getGlobalContext().Core.setPatientShort(null);
	}

	private void addNewPathwayRow(PatientPathwaysAwaitingValidationWorklistVo pathway)
	{
		grdResultsRow pathwayRow = form.grdResults().getRows().newRow();
		
		pathwayRow.setcolNHS(pathway.getPatientIsNotNull() && pathway.getPatient().getDisplayId() != null ? pathway.getPatient().getDisplayId().getValue() : null);
		pathwayRow.setCellcolNHSTooltip(pathwayRow.getcolNHS());
		
		pathwayRow.setcolName(pathway.getPatientIsNotNull() && pathway.getPatient().getName() != null ? pathway.getPatient().getName().toStringSurnameFirst() : null);
		pathwayRow.setCellcolNameTooltip(pathwayRow.getcolName());
		
		pathwayRow.setcolSex(pathway.getPatientIsNotNull() && pathway.getPatient().getSexIsNotNull() ? pathway.getPatient().getSex().getIItemText() : null );
		pathwayRow.setCellcolSexTooltip(pathwayRow.getcolSex());
		
		pathwayRow.setcolJStartDate(pathway.getStartDate());
		pathwayRow.setCellcolJStartDateTooltip(pathwayRow.getcolJStartDate() != null ? pathwayRow.getcolJStartDate().toString() : null);
		
		pathwayRow.setcolStatus(pathway.getCurrentClockIsNotNull() ? formatRTTStatusHistoryTooltip(pathway.getCurrentClock().getCurrentRTTStatus()) : null);
		pathwayRow.setCellcolStatusTooltip(pathwayRow.getcolStatus());
		
		pathwayRow.setcolPathwaySpecialty(pathway.getPathwayIsNotNull() && pathway.getPathway().getSpecialtyIsNotNull() ? pathway.getPathway().getSpecialty().getIItemText(): null);
		pathwayRow.setCellcolPathwaySpecialtyTooltip(pathwayRow.getcolPathwaySpecialty());
		
		//WDEV-21431
		pathwayRow.setcolReferralService(pathway.getServiceIsNotNull() && pathway.getService().getServiceNameIsNotNull() ? pathway.getService().getServiceName() : null);
		pathwayRow.setCellcolReferralServiceTooltip(pathwayRow.getcolReferralService());
		
		pathwayRow.setcolTEndDate(pathway.getCurrentClock() != null ? pathway.getCurrentClock().getTargetClockEnd() : null);
		pathwayRow.setCellcolTEndDateTooltip(pathwayRow.getcolTEndDate()!= null ? pathwayRow.getcolTEndDate().toString() : null);
		
		pathwayRow.setcolRespConsultant(pathway.getResponsibleConsultantIsNotNull() ? pathway.getResponsibleConsultant().getIMosName() : null);
		pathwayRow.setCellcolRespConsultantTooltip(pathwayRow.getcolRespConsultant());
		
		pathwayRow.setcolNextValidDate(pathway.getNextValidationDate());
		pathwayRow.setCellcolNextValidDateTooltip(pathwayRow.getcolNextValidDate() != null ? pathwayRow.getcolNextValidDate().toString() : null);
		
		pathwayRow.setValue(pathway);
	}
	
	private String formatRTTStatusHistoryTooltip(PathwayRTTStatusVo statusDetails)
	{	
		String text = "";
		if (statusDetails != null && statusDetails.getRTTStatusIsNotNull())
		{	
			text = statusDetails.getRTTStatus().getNationalCodeIsNotNull() ?  statusDetails.getRTTStatus().getNationalCode().toString() + ". " + statusDetails.getRTTStatus().getDescription() : statusDetails.getRTTStatus().getDescription();
		}
  		return text;
	}

	private boolean isSearchCriteriaValid()
	{
		ArrayList<String> errorList = new ArrayList<String>();
		
		if (Boolean.FALSE.equals(form.chkInclude().getValue()) && form.dteStartDate().getValue() == null)
		{
			errorList.add("Next Validation Start Date is mandatory");
		}
		
		if (Boolean.FALSE.equals(form.chkInclude().getValue()) && form.dteEndDate().getValue() == null)
		{
			errorList.add("Next Validation End Date is mandatory");
		}
		
		if (Boolean.FALSE.equals(form.chkInclude().getValue()) && form.dteStartDate().getValue() != null && form.dteEndDate().getValue()!= null && form.dteStartDate().getValue().isGreaterThan(form.dteEndDate().getValue()))
		{
			errorList.add("'Next Validation Start Date' cannot be greater than 'Next Validation End Date'");//WDEV-21615
		}
		
		if (Boolean.TRUE.equals(form.chkInclude().getValue()) && form.intRTTWeeks().getValue() == null)
		{
			errorList.add("RTT date in 'no. of weeks' is mandatory");
		}
		
		if (Boolean.TRUE.equals(form.chkInclude().getValue()) && form.intNotValidated().getValue() == null)
		{
			errorList.add("Pathway not validated in 'no. of weeks' is mandatory");
		}
		
		if (errorList != null && errorList.size() > 0)
		{
			engine.showErrors(errorList.toArray(new String[errorList.size()]));
			clearContextVariables();
			form.grdResults().getRows().clear();
			return false;
		}
		
		return true;
	}

	@Override
	protected void onContextMenuItemClick(int menuItemID, ims.framework.Control sender) throws ims.framework.exceptions.PresentationLogicException
	{
		switch(menuItemID)
		{
			case GenForm.ContextMenus.PathwaysNamespace.PathwaysAwaitingValidation.VIEW:
				viewPathway();
			break;
			
			//WDEV-21255
			case GenForm.ContextMenus.PathwaysNamespace.PathwaysAwaitingValidation.VALIDATION_COMPLETE:
				completeValidation();
			break;
			
			//WDEV-21389
			case GenForm.ContextMenus.PathwaysNamespace.PathwaysAwaitingValidation.VIEWREFERRALDETAILS:
				viewReferralDetails();
			break;

		}
	}


	private void completeValidation()
	{
		
		if (form.grdResults().getValue() != null && form.grdResults().getValue().getPatient() != null)
		{
			form.getGlobalContext().Core.setPatientShort(new PatientShort(form.grdResults().getValue().getPatient().getID_Patient(), form.grdResults().getValue().getPatient().getVersion_Patient()));
			form.getGlobalContext().Pathways.setSelectedPatientPathwayJourney(form.grdResults().getValue());
			form.getGlobalContext().Pathways.setSelectedPathway(form.grdResults().getValue() != null ? form.grdResults().getValue().getPathway() : null);
		}

		engine.open(form.getForms().Pathways.PatientPathwayValidationCompleteDialog);
		
	}

	private void viewPathway()
	{
		//WDEV-21155
//		engine.open(form.getForms().Pathways.PatientJourney, new Object[] {VIEW_PATHWAY_FROM_VALIDATION_WORKLIST});	
//		form.getGlobalContext().Core.setPatientShort(new PatientShort(form.grdResults().getValue().getPatient().getID_Patient(), form.grdResults().getValue().getPatient().getVersion_Patient()));
//		form.getGlobalContext().Pathways.setSelectedPatientPathwayJourney(form.grdResults().getValue());
//		form.getGlobalContext().Pathways.setSelectedPathway(form.grdResults().getValue() != null ? form.grdResults().getValue().getPathway() : null);

		form.getGlobalContext().Pathways.setPatientPathwaysAwaitingValidationSearchCriteria(getSearchCriteria()); //WDEV-21431 Set global search criteria
		ContextMenu_View_Pathway_Selected = Boolean.TRUE; //WDEV-21431
		
		engine.open(form.getForms().RefMan.RTTManagement, new Object[] {VIEW_RTTMANAGEMENT_FROM_VALIDATION_WORKLIST, form.getGlobalContext().Pathways.getSelectedPatientPathwayJourney()});			
	}

	//WDEV-21389
	private void viewReferralDetails()
	{
		CatsReferralListVo catsVo = domain.getCatsReferral(form.grdResults().getValue());
		
		form.getGlobalContext().RefMan.setCatsReferral(catsVo);
		form.getGlobalContext().Core.setPatientShort(new PatientShort(form.grdResults().getValue().getPatient().getID_Patient(), form.grdResults().getValue().getPatient().getVersion_Patient()));
		form.getGlobalContext().Core.setCurrentCareContext(domain.getCareContextShort(catsVo.getCareContext()));

		engine.open(form.getForms().RefMan.ReferralDetailsDialog);
	}
	
	
	@Override
	protected void onGrdResultsGridHeaderClicked(int column) throws PresentationLogicException
	{
		sortOrder(column);
		if (form.getLocalContext().getlcSelectedPathwayIsNotNull())
			form.grdResults().setValue(form.getLocalContext().getlcSelectedPathway());	
		updateControlState();
	}

	private void sortOrder(int column)
	{
		PatientPathwaysAwaitingValidationWorklistVoCollection pathwaysList = form.grdResults().getValues();
		
		if (pathwaysList == null || pathwaysList.size() < 2)
			return ;
		
		if (column == COLUMN_RESP_CONSULTANT)
		{
			form.getLocalContext().setlcRespConsultantSortOrder(SortOrder.ASCENDING.equals(form.getLocalContext().getlcRespConsultantSortOrder())? SortOrder.DESCENDING : SortOrder.ASCENDING);
			form.getLocalContext().setlcPatientNameSortOrder(null);
			pathwaysList.sort(new PathwaysAwaitingValidatioRespConsultantComparator(form.getLocalContext().getlcRespConsultantSortOrder()));			
		}
		
		if (column == COLUMN_PATIENTNAME)
		{
			form.getLocalContext().setlcPatientNameSortOrder(SortOrder.ASCENDING.equals(form.getLocalContext().getlcPatientNameSortOrder())? SortOrder.DESCENDING : SortOrder.ASCENDING);
			form.getLocalContext().setlcRespConsultantSortOrder(null);
			pathwaysList.sort(new PathwaysAwaitingValidationPatientNameComparator(form.getLocalContext().getlcPatientNameSortOrder()));
		}
		
		populateScreenFromData(pathwaysList);
	}
	
	public class PathwaysAwaitingValidationPatientNameComparator implements Comparator<PatientPathwaysAwaitingValidationWorklistVo>
	{
		private int order = 1;
		
		public PathwaysAwaitingValidationPatientNameComparator()
		{
			order = 1;
		}
		
		public PathwaysAwaitingValidationPatientNameComparator(SortOrder order)
		{
			this.order = SortOrder.DESCENDING.equals(order) ? -1 : 1;
		}
		
		public int compare(PatientPathwaysAwaitingValidationWorklistVo o1, PatientPathwaysAwaitingValidationWorklistVo o2)
		{
			if(o1 != null && o1.getPatientIsNotNull() && o1.getPatient().getNameIsNotNull() && 
			   o2 != null && o2.getPatientIsNotNull() && o2.getPatient().getNameIsNotNull())
				return order* o1.getPatient().getName().compareTo(o2.getPatient().getName());
			
			if (o1 == null || !o1.getPatientIsNotNull() || !o1.getPatient().getNameIsNotNull())
				return -1 * order;
			
			if (o2 == null || !o2.getPatientIsNotNull() || !o2.getPatient().getNameIsNotNull())
				return order;
			
			return 0;
		}
	}
	
	public class PathwaysAwaitingValidatioRespConsultantComparator implements Comparator<PatientPathwaysAwaitingValidationWorklistVo>
	{
		private int order = 1;
		
		public PathwaysAwaitingValidatioRespConsultantComparator()
		{
			order = 1;
		}
		
		public PathwaysAwaitingValidatioRespConsultantComparator(SortOrder order)
		{
			this.order = SortOrder.DESCENDING.equals(order) ? -1 : 1;
		}
		
		public int compare(PatientPathwaysAwaitingValidationWorklistVo o1, PatientPathwaysAwaitingValidationWorklistVo o2)
		{
			if (o1 != null && o1.getResponsibleConsultant() != null  && o1.getResponsibleConsultant().getName() != null && o1.getResponsibleConsultant().getName().getSurname() != null 
					&& o2 != null && o2.getResponsibleConsultant() != null  && o2.getResponsibleConsultant().getName() != null && o2.getResponsibleConsultant().getName().getSurname() != null)
			{
				int compareBySurname = o1.getResponsibleConsultant().getName().getSurname().compareToIgnoreCase(o2.getResponsibleConsultant().getName().getSurname());
				if (0 != compareBySurname)
				{
					return order * compareBySurname;
				}
				if (o1.getResponsibleConsultant().getName().getForename() != null 
						&& o2.getResponsibleConsultant().getName().getForename() != null)
					return order*o1.getResponsibleConsultant().getName().getForename().compareToIgnoreCase(o2.getResponsibleConsultant().getName().getForename());
				
			}
			if (o1 == null || o1.getResponsibleConsultant() == null || o1.getResponsibleConsultant().getName() == null || o1.getResponsibleConsultant().getName().getSurname() == null)
				return -1 * order;

			if (o2 == null || o2.getResponsibleConsultant() == null || o2.getResponsibleConsultant().getName() == null || o2.getResponsibleConsultant().getName().getSurname() == null)
				return order;
			
			return 0;
		}		
	}

	@Override
	protected void onFormDialogClosed(FormName formName, DialogResult result) throws PresentationLogicException
	{
		
		//WDEV-21155 Check dialog result OK & save patient pathway journey 
		if(formName.equals(form.getForms().Pathways.PatientPathwayValidationCompleteDialog))
		{
			if(result.equals(DialogResult.OK))
			{
				PatientPathwaysAwaitingValidationWorklistVo patientPathwayJourney = form.getGlobalContext().Pathways.getPatientPathwaysAwaitingValidationWorklistVo();
				
				try
				{
					domain.savePatientPathwayJourney(patientPathwayJourney);
				}
				catch (DomainInterfaceException e)
				{
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				catch (StaleObjectException e)
				{
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
				
			}
			
		}

		//WDEV-21431
		if (form.getForms().RefMan.ReferralServiceSelectionDialog.equals(formName))
		{
			if (DialogResult.OK.equals(result))
			{
				if (form.getGlobalContext().RefMan.getReferralServiceSearchList() != null 
						&& form.getGlobalContext().RefMan.getReferralServiceSearchList().size() == 1)
				{
					if(form.getGlobalContext().RefMan.getReferralServiceSearchList().get(0) != null)
					{
						form.qmbService().newRow(form.getGlobalContext().RefMan.getReferralServiceSearchList().get(0), form.getGlobalContext().RefMan.getReferralServiceSearchList().get(0).getServiceName());
					}
					form.qmbService().setValue(form.getGlobalContext().RefMan.getReferralServiceSearchList().get(0));
					setServiceLabelValue(null);
				}
				else
				{
					form.lblServices().setVisible(true);
					setServiceLabelValue(listServices());
					form.qmbService().clear();
				}
			}
		}
		else
			open();//WDEV-22441 //Redisplay worklist, without the now Validation Completed row if necessary - user may have cancelled out of dialog

	}

	@Override
	protected void onChkIncludeValueChanged() throws PresentationLogicException
	{
		if (Boolean.FALSE.equals(form.chkInclude().getValue()))
		{
			form.intRTTWeeks().setValue(null);
			form.intNotValidated().setValue(null);
			form.dteStartDate().setValue(new Date());
			form.dteEndDate().setValue(new Date().addDay(7));
			//intializeServices(); //WDEV-21431 -- this is in comment because WDEV-22441 
		}
		else if (Boolean.TRUE.equals(form.chkInclude().getValue()))
		{
			form.dteEndDate().setValue(null);
			form.dteStartDate().setValue(null);
			//form.qmbService().setValue(null); //WDEV-21431
			//form.lblServices().setValue(null); //WDEV-21431
			//form.getGlobalContext().RefMan.setReferralServiceSearchList(null); //WDEV-21431
		}
		updateControlState();		
	}
	
	//WDEV-21431
	protected void onImbServiceSearchClick() throws PresentationLogicException
	{
		if (form.qmbService().getValue() != null)
		{
			form.getGlobalContext().RefMan.setReferralServiceSearchList(new ServiceShortVoCollection());
			form.getGlobalContext().RefMan.getReferralServiceSearchList().add(form.qmbService().getValue());
		}		
		engine.open(form.getForms().RefMan.ReferralServiceSelectionDialog);
	}
	
	//WDEV-21431
	@Override
	protected void onQmbServiceValueChanged() throws PresentationLogicException
	{
		form.getGlobalContext().RefMan.setReferralServiceSearchList(null); 
		setServiceLabelValue(listServices());
	}

	//WDEV-21431
	private void setServiceLabelValue(String services) 
	{
		form.lblServices().setValue(null);
		form.lblServices().setTooltip(null);
		
		if(services == null || services.length() == 0)
			return;
		
		form.lblServices().setValue(services.toString().length() >= 105 ? services.toString().substring(0, 105) + "..." : services.toString());
		form.lblServices().setTooltip(services);
	}

	//WDEV-21431
	private String listServices() 
	{
		if (form.getGlobalContext().RefMan.getReferralServiceSearchList() == null 
				|| form.getGlobalContext().RefMan.getReferralServiceSearchList().size() == 0)
			return null;
		
		StringBuffer displayText = new StringBuffer();
		
		for (ServiceShortVo serviceReferral : form.getGlobalContext().RefMan.getReferralServiceSearchList())
		{
			if (serviceReferral == null)
				continue;
			
			if (displayText.length() > 0)
				displayText.append(", ");
			
			displayText.append(serviceReferral.getServiceName());
		}
		
		if (displayText.length() > 0)
			displayText.insert(0, "Services:       ");
		
		return displayText.toString();
	}

	//WDEV-21431
	@Override
	protected void onQmbServiceTextSubmited(String value) throws PresentationLogicException
	{
		form.qmbService().clear();
		
		ServiceShortVoCollection services = domain.getReferralServices(value);
		
		for(ServiceShortVo service : services)
		{
			if(service == null)
				continue;
			
			form.qmbService().newRow(service, service.getServiceName());
		}
		
		form.qmbService().showOpened();
	}

	//WDEV-21431
	@Override
	protected void onFormClosing(CancelArgs args) throws PresentationLogicException
	{
		if (! ContextMenu_View_Pathway_Selected)
		{
			clearSearchCriteriaAndResults();
			form.getLocalContext().setlcSelectedPathway(null);
			form.getGlobalContext().Pathways.setPatientPathwaysAwaitingValidationSearchCriteria(null);
			form.getGlobalContext().RefMan.setReferralStatusListFilter(null); 
			form.getGlobalContext().RefMan.setReferralServiceSearchList(null);
		}
	}
}
