/FileExtraction/Java_unseen/IMS-MAXIMS_openMAXIMS/Source Library/openmaxims_workspace/Pathways/src/ims/pathways/forms/patientjourney/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 Marius Mihalec using IMS Development Environment (version 1.60 build 2838.16667)
// Copyright (C) 1995-2007 IMS MAXIMS plc. All rights reserved.

package ims.pathways.forms.patientjourney;

import ims.RefMan.vo.lookups.ReferralApptStatus;
import ims.configuration.AppRight;
import ims.configuration.gen.ConfigFlag;
import ims.core.vo.ReferralLiteVo;
import ims.core.vo.ReferralLiteVoCollection;
import ims.core.vo.enums.PatientJourneyAction;
import ims.domain.exceptions.StaleObjectException;
import ims.framework.FormName;
import ims.framework.enumerations.DialogResult;
import ims.framework.enumerations.SortOrder;
import ims.framework.exceptions.CodingRuntimeException;
import ims.framework.exceptions.PresentationLogicException;
import ims.framework.utils.Color;
import ims.framework.utils.Date;
import ims.framework.utils.DateTime;
import ims.pathways.configuration.vo.PathwayRefVo;
import ims.pathways.vo.PathwayCurrentClockForRttStatusVo;
import ims.pathways.vo.PathwayHistoryVoCollection;
import ims.pathways.vo.PathwayLiteVo;
import ims.pathways.vo.PathwayRTTCurrentStatusVo;
import ims.pathways.vo.PathwayRTTCurrentStatusVoCollection;
import ims.pathways.vo.PatientJourneyBreachReasonListVo;
import ims.pathways.vo.PatientJourneyCommentLiteVo;
import ims.pathways.vo.PatientJourneyCommentLiteVoCollection;
import ims.pathways.vo.PatientJourneyCommentsVo;
import ims.pathways.vo.PatientJourneyDummyVo;
import ims.pathways.vo.PatientJourneyEventInterfaceVo;
import ims.pathways.vo.PatientJourneyEventInterfaceVoCollection;
import ims.pathways.vo.PatientJourneyInterfaceVo;
import ims.pathways.vo.PatientJourneyJourneyTargetInterfaceVo;
import ims.pathways.vo.PatientJourneySearchCriteriaVo;
import ims.pathways.vo.PatientJourneyShortVo;
import ims.pathways.vo.PatientJourneyShortVoCollection;
import ims.pathways.vo.PatientJourneyTargetInterfaceVo;
import ims.pathways.vo.PatientJourneyTargetRefVo;
import ims.pathways.vo.PatientPathwayJourneyRefVo;
import ims.pathways.vo.PatwayHistoryDummyVo;
import ims.pathways.vo.TargetReadjustmentVoCollection;
import ims.pathways.vo.enums.TargetReadjustmentsAction;
import ims.pathways.vo.lookups.EventStatus;
import ims.vo.interfaces.IPatientJourneyEvent;
import ims.vo.interfaces.IPatientJourneyTarget;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Comparator;

public class Logic extends BaseLogic
{
	
	private static final long serialVersionUID = 1L;
	
	private static final Integer NEW_COMMENT_MODE = new Integer(1);
	private static final Integer VALIDATE_MODE = new Integer(2);
	private static final Integer VIEW_LAST_COMMENT_MODE = new Integer(3);
	private static final Integer VIEW_PATHWAY_FROM_VALIDATION_WORKLIST = new Integer(0);
	@Override
	protected void onFormOpen(Object[] args) throws ims.framework.exceptions.PresentationLogicException
	{	
		//WDEV-21179 
		form.lblProfile().setVisible(false);
		form.cmbPatientJourney().setVisible(false);
		form.btnView().setVisible(false);
		//end WDEV-21179 
		//launched from worklist
		
		if(form.getGlobalContext().Pathways.getSelectedPatientPathwayJourneyIsNotNull())
		{	
			displayJourney();	
			if (args != null && args.length > 0 && args[0] instanceof Integer && VALIDATE_MODE.equals(args[0]))
			{
				engine.open(form.getForms().Pathways.PatientJourneyComment, new Object[] { VALIDATE_MODE, PatientJourneyAction.ADDPATHWAYCOMMENT, null});
			}
			else if (args != null && args.length > 0 && args[0] instanceof Integer && VIEW_LAST_COMMENT_MODE.equals(args[0]))
			{
				engine.open(form.getForms().Pathways.PatientJourneyComment, new Object[] { VIEW_LAST_COMMENT_MODE, null, null});
			}
		}
		else
		{
			open();
			if (!(form.getGlobalContext().Core.getPatientShortIsNotNull() && form.getGlobalContext().Pathways.getPatientJourneySearchCriteriaIsNotNull() && form.getGlobalContext().Core.getPatientShort().equals(form.getGlobalContext().Pathways.getPatientJourneySearchCriteria().getPatient())) ||
				(form.getGlobalContext().RefMan.getCatsReferralIsNotNull()	&& 
				!(form.getGlobalContext().Pathways.getPatientJourneySearchCriteriaIsNotNull() && form.getGlobalContext().RefMan.getCatsReferral().equals(form.getGlobalContext().Pathways.getPatientJourneySearchCriteria().getCatsReferral()))	))
				form.getGlobalContext().Pathways.setPatientJourneySearchCriteria(null);
			
			if (form.getGlobalContext().Pathways.getPatientJourneySearchCriteriaIsNotNull())
			{
				setSearchCriteria(form.getGlobalContext().Pathways.getPatientJourneySearchCriteria());
				onBtnViewClick();
			}		
		}
		
		// WDEV-20119
		form.btnSetCancerPathway().setVisible(false);
		viewSelectedJourney();//WDEV-22775
		updateLinkButtons(args);
		//WDEV-18414 
		//	form.imbComments().setEnabled(false);
		//	form.imbComments().setTooltip(null);
		
	}
	
	private void updateLinkButtons(Object[] args)
	{
		form.lnkReturn().setVisible(form.getGlobalContext().Pathways.getSelectedPatientPathwayJourneyIsNotNull() && (args == null || args .length  < 1 ));
		form.lnkRetunToPathway().setVisible(args != null && args.length > 0 && args[0] instanceof Integer && (VIEW_PATHWAY_FROM_VALIDATION_WORKLIST.equals(args[0])));	
	}

	private PatientJourneySearchCriteriaVo getSearchCriteria()
	{
		PatientJourneySearchCriteriaVo searchCriteria = new PatientJourneySearchCriteriaVo();
		
		searchCriteria.setSelectedReferral(form.cmbReferrals().getValue());
		if (form.cmbPatientJourney().getValue() instanceof PatientJourneyDummyVo)
			searchCriteria.setJourney((PatientJourneyDummyVo) form.cmbPatientJourney().getValue());
		else if (form.cmbPatientJourney().getValue() instanceof PatientJourneyDummyVo)
			searchCriteria.setJourneyHistory((PatwayHistoryDummyVo) form.cmbPatientJourney().getValue());
		
		searchCriteria.setPatient(form.getGlobalContext().Core.getPatientShort());
		searchCriteria.setCatsReferral(form.getGlobalContext().RefMan.getCatsReferral());
		
		return searchCriteria;
	}
	
	private void setSearchCriteria(PatientJourneySearchCriteriaVo patientJourneySearchCriteriaVo) throws PresentationLogicException 
	{
		form.cmbReferrals().setValue(patientJourneySearchCriteriaVo.getSelectedReferral());
		onCmbReferralsValueChanged();
		if (patientJourneySearchCriteriaVo.getJourneyIsNotNull())
		{
			form.cmbPatientJourney().setValue(patientJourneySearchCriteriaVo.getJourney());
		}
		else if (patientJourneySearchCriteriaVo.getJourneyHistoryIsNotNull())
		{
			form.cmbPatientJourney().setValue(patientJourneySearchCriteriaVo.getJourneyHistory());
		}
		onCmbPatientJourneyValueChanged();
	}
	
	private void displayJourney() throws PresentationLogicException
	{
		if(form.getGlobalContext().Pathways.getSelectedPatientPathwayJourneyIsNotNull())
		{
			loadReferrals(false);
			ReferralLiteVo voReferral =  domain.getReferralByJourney(form.getGlobalContext().Pathways.getSelectedPatientPathwayJourney());
			form.cmbReferrals().setValue(voReferral);
			cmbReferralValueChanged();
			
			for(int i=0;i<form.cmbPatientJourney().getValues().size();i++)
			{
				if(form.cmbPatientJourney().getValues().get(i) instanceof PatientJourneyDummyVo)
				{
					if( ((PatientJourneyDummyVo)form.cmbPatientJourney().getValues().get(i)).getPatientJourneyID().equals(form.getGlobalContext().Pathways.getSelectedPatientPathwayJourney().getID_PatientPathwayJourney()))
					{
						form.cmbPatientJourney().setValue(form.cmbPatientJourney().getValues().get(i));
						break;
					}
				}
				else if(form.cmbPatientJourney().getValues().get(i) instanceof PatwayHistoryDummyVo)
				{
					if( ((PatwayHistoryDummyVo)form.cmbPatientJourney().getValues().get(i)).getPatientJourneyID().equals(form.getGlobalContext().Pathways.getSelectedPatientPathwayJourney().getID_PatientPathwayJourney()))
					{
						form.cmbPatientJourney().setValue(form.cmbPatientJourney().getValues().get(i));
						break;
					}
				}
			}
			viewSelectedJourney();
		}
		
	}
	
	@Override
	protected void onBtnViewClick() throws ims.framework.exceptions.PresentationLogicException
	{
		viewSelectedJourney();
	}
	
	protected void onBtnSetCancerPathwayClick() throws ims.framework.exceptions.PresentationLogicException
	{
		// Load Dialog to get the CancerPathwayDate
		engine.open(form.getForms().Core.DateEntryDialog);
	}
	
	@Override
	protected void onCmbPatientJourneyValueChanged() throws ims.framework.exceptions.PresentationLogicException
	{		
		updateControlsState();
		form.getGlobalContext().Pathways.setSelectedPatientPathwayJourney(form.getGlobalContext().Pathways.getPatientJourneyComments());
		//WDEV-18135
		if (form.cmbPatientJourney().getValue() == null)
		{
			form.patientJourney().clear();
			form.txtNextValidationdate().setValue(null);
			form.txtLastValidation().setValue(null);//WDEV-22775
		}

	}
	@Override
	protected void onCmbReferralsValueChanged() throws ims.framework.exceptions.PresentationLogicException
	{
		cmbReferralValueChanged();
		
		if (form.cmbReferrals().getValue() == null)
		{
			form.patientJourney().clear();
			form.txtNextValidationdate().setValue(null);
			form.txtLastValidation().setValue(null);//WDEV-22775
		}
	}

	private void cmbReferralValueChanged() throws PresentationLogicException
	{
		populateRTTBreachDate(form.cmbReferrals().getValue());
		
		if(form.cmbReferrals().getValue() != null)
		{
			populateRTTStatus(form.cmbReferrals().getValue().getID_Referral());
			loadPatientJourneys();
			viewSelectedJourney();//WDEV-22775
		}
		else
		{
			form.getLocalContext().setbDisplayRttStatusDetailsField(false);
			updateControlsState();
		}
		
	}
	

	private void populateAdjustedRTTBreachDate(ReferralLiteVo value, Date breachDate)
	{	
		int adjustedDays = domain.getCurrentPauseDetails(form.cmbReferrals().getValue());
		
		form.lblAdjusted().setVisible(form.txtRTTBreachDate().isVisible() && adjustedDays != 0);
		form.txtAdjustedDate().setEnabled(false);
		form.txtAdjustedDate().setVisible(form.txtRTTBreachDate().isVisible() && adjustedDays != 0);
		form.txtAdjustedDate().setValue(form.txtRTTBreachDate().isVisible() && adjustedDays != 0 && breachDate != null ? breachDate.addDay(adjustedDays).toString() : null);	
	}

	private void populateRTTBreachDate(ReferralLiteVo value)
	{
		Date breachDate = domain.getRTTBreachDate(form.cmbReferrals().getValue());
		
		form.lblRTTBreachDate().setVisible(breachDate != null);
		form.txtRTTBreachDate().setEnabled(false);
		form.txtRTTBreachDate().setVisible(breachDate != null);
		form.txtRTTBreachDate().setValue(breachDate != null ? breachDate.toString() : null);
		
		populateAdjustedRTTBreachDate(value, breachDate);
	}

	private void populateRTTStatus(Integer id_Referral)
	{
		form.txtRttCurrentStatus().setValue(null);
		form.txtRttCurrentStatus().setTooltip(" ");
		form.getLocalContext().setbDisplayRttStatusDetailsField(false);
		
		PathwayCurrentClockForRttStatusVo currentCLock = domain.getRTTStatus(id_Referral);
		PathwayRTTCurrentStatusVo currentRTTStatus = currentCLock != null ? currentCLock.getCurrentRTTStatus() : null;
		PathwayRTTCurrentStatusVoCollection rttHistory = currentCLock != null ? currentCLock.getRTTStatusHistory() : null;
		
		if (rttHistory != null && rttHistory.size() > 0)
			rttHistory.sort(SortOrder.DESCENDING);
		
		if (Boolean.TRUE.equals(ConfigFlag.DOM.RTT_STATUS_POINT_FUNCTIONALITY.getValue()) && currentRTTStatus != null)
		{
			if (currentRTTStatus != null)
				form.txtRttCurrentStatus().setValue(currentRTTStatus.getRTTStatus().getNationalCodeIsNotNull() ?  currentRTTStatus.getRTTStatus().getNationalCode().toString() + ". " + currentRTTStatus.getRTTStatus().getDescription() : currentRTTStatus.getRTTStatus().getDescription());
			String rttHistoryTooltip = formatRTTStatusHistoryTooltip(true, currentRTTStatus);
			
    		if (rttHistory != null && rttHistory.size() > 0)
    		{
    			if (rttHistory.size() > 1 || ( rttHistory.size() == 1 && !rttHistory.get(0).equals(currentRTTStatus)) )
    				rttHistoryTooltip += "RTT Status History: <br>";
    			for (int i = rttHistory.get(0).equals(currentRTTStatus) ? 1 : 0 ; i < rttHistory.size(); i++)
    			{    				
    				rttHistoryTooltip += formatRTTStatusHistoryTooltip(false, rttHistory.get(i));
    			}					
    		}
    		
    		form.txtRttCurrentStatus().setTooltip(rttHistoryTooltip);
    		form.getLocalContext().setbDisplayRttStatusDetailsField(true);
		}		
	}

	private String formatRTTStatusHistoryTooltip(boolean currentStatus, PathwayRTTCurrentStatusVo statusDetails)
	{	
		String tooltip = "";
		if (statusDetails != null)
		{	
    		if (Boolean.TRUE.equals(currentStatus))
    			tooltip = "RTT Current Status: <br>";
    		
    		String hcpName = statusDetails.getStatusByIsNotNull() && statusDetails.getStatusBy().getNameIsNotNull() ? statusDetails.getStatusBy().getName().toString() : "";
    		
    		String rttStatusDetails = "";
    		if (statusDetails.getRTTStatusIsNotNull())
    			rttStatusDetails = statusDetails.getRTTStatus().getNationalCodeIsNotNull() ?  statusDetails.getRTTStatus().getNationalCode().toString() + ". " + statusDetails.getRTTStatus().getDescription() : statusDetails.getRTTStatus().getDescription();
    			
    		tooltip += statusDetails.getStatusDateTime()+ " - " + hcpName + " - " + rttStatusDetails + "<br>";  
		}
  		return tooltip;
	}

	private void open() throws PresentationLogicException 
	{
		loadReferrals(true);
	}		
	private void loadReferrals(boolean searchAfterCatsReferral) throws PresentationLogicException
	{
		form.cmbReferrals().clear();
		updateControlsState();
		
		//ReferralLiteVoCollection referrals = domain.listReferrals(form.getGlobalContext().Core.getPatientShort());
		ReferralLiteVoCollection referrals = domain.listReferralWithPathways(form.getGlobalContext().Core.getPatientShort()); //wdev-14124
		if(referrals != null)
		{
			for(int x = 0; x < referrals.size(); x++)
			{
				//WDEV-19927 
				if (referrals.get(x).getCatsReferralDetailsIsNotNull())
				{
					String dateOfReferral = referrals.get(x).getCatsReferralDetails().getReferralDetailsIsNotNull() && referrals.get(x).getCatsReferralDetails().getReferralDetails().getDateOfReferralIsNotNull() ? referrals.get(x).getCatsReferralDetails().getReferralDetails().getDateOfReferral().toString() : " '' ";
					String urgency = referrals.get(x).getCatsReferralDetails().getUrgencyIsNotNull() ? referrals.get(x).getCatsReferralDetails().getUrgency().getIItemText() : " '' ";
					String service = referrals.get(x).getCatsReferralDetails().getReferralDetailsIsNotNull() && referrals.get(x).getCatsReferralDetails().getReferralDetails().getServiceIsNotNull() ? referrals.get(x).getCatsReferralDetails().getReferralDetails().getService().getServiceName() : " '' ";
					String consultant = referrals.get(x).getCatsReferralDetails().getReferralDetailsIsNotNull() && referrals.get(x).getCatsReferralDetails().getReferralDetails().getReferringConsultantIsNotNull() ? referrals.get(x).getCatsReferralDetails().getReferralDetails().getReferringConsultant().toString() : " '' ";
					
					String comboValue = dateOfReferral + " - " + urgency + " - " + service + " - " + consultant;
					form.cmbReferrals().newRow(referrals.get(x), comboValue);
				}
				else
					form.cmbReferrals().newRow(referrals.get(x), referrals.get(x).toString());
			}
			
			// wdev-7327 default referral into combo if only 1
			if (referrals.size() == 1)
			{
				form.cmbReferrals().setValue(referrals.get(0));
				cmbReferralValueChanged();
			}
			
			if (Boolean.TRUE.equals(searchAfterCatsReferral) && referrals.size() > 1 && form.getGlobalContext().RefMan.getCatsReferralIsNotNull() )
			{
				form.cmbReferrals().setValue(domain.getReferralFromSelectedCatsReferral(form.getGlobalContext().RefMan.getCatsReferral().getID_CatsReferral()));
				cmbReferralValueChanged();
			}
		}
	}
	private void loadPatientJourneys() throws PresentationLogicException
	{
		form.cmbPatientJourney().clear();
		updateControlsState();
		
		PatientJourneyShortVoCollection journeys = domain.listPatientJourneyShortByReferral(form.cmbReferrals().getValue());
		
		if(journeys != null)
		{
			PatientJourneyDummyVo firstDummy=null;
			ArrayList<String> listOfPreviousPathways = new ArrayList<String>();
			
			for(int x = 0; x < journeys.size(); x++)
			{
				PatientJourneyDummyVo voDummy = new PatientJourneyDummyVo();
				if (x == 0)
					firstDummy = voDummy;
				voDummy.setPatientJourneyID(journeys.get(x).getID_PatientPathwayJourney());
				form.cmbPatientJourney().newRow(voDummy, journeys.get(x).toString());
		
				PathwayHistoryVoCollection voHistory = journeys.get(x).getPathwayHistory();
				
				for (int i = voHistory.size()-1 ; i >= 0 ; i--)
				//for (int i = 0; i < voHistory.size() ; i++)
				{
					PatwayHistoryDummyVo voPathwayDummy = new PatwayHistoryDummyVo();
					voPathwayDummy.setPatientJourneyID(voDummy.getPatientJourneyID());
					voPathwayDummy.setPathwayHistoryID(voHistory.get(i).getPathway().getID_Pathway());
					voPathwayDummy.setIterator(i);
					
					//WDEV-14576
					StringBuffer text = new StringBuffer("    ");
					text.append(voHistory.get(i).getPathway().toString());		
					text.append(voHistory.get(i).getSystemInformation().getCreationUser()!= null ? " - " + voHistory.get(i).getSystemInformation().getCreationUser(): ""); //WDEV-20078
					text.append(voHistory.get(i).getSystemInformation().getCreationUser()!= null? ", " + voHistory.get(i).getSystemInformation().getCreationDateTime(): ""); //WDEV-20078			
					form.cmbPatientJourney().newRow(voPathwayDummy,text.toString(),Color.Red);
					listOfPreviousPathways.add(text.toString());
				}		
			}
			
			form.cmbPatientJourney().setTooltip(null);//WDEV-20423
						
			//WDEV-17914
			if (listOfPreviousPathways.size() > 0)
			{
				String result = "";

				for (int a = 0; a < listOfPreviousPathways.size(); a++)
					result = result + listOfPreviousPathways.get(a) + "<br>";

				form.cmbPatientJourney().setTooltip(result.toString());
			}
			
			// wdev-7327 - default journey into combo if only 1
			if (journeys.size()== 1 && firstDummy != null)
			{
				form.cmbPatientJourney().setValue(firstDummy);
				onCmbPatientJourneyValueChanged();
				
				if (listOfPreviousPathways.size() == 0)
					viewSelectedJourney(); //WDEV-19927 
			}
			
		}
	}
	
	private void updateControlsState()
	{
		boolean referralSelected = form.cmbReferrals().getValue() != null;
		if(!referralSelected)
			form.cmbPatientJourney().clear();
		
		//wdev-20782
		boolean isCatsTransferred = false;
		if( form.cmbReferrals().getValue() != null && form.cmbReferrals().getValue().getCatsReferralDetailsIsNotNull() && form.cmbReferrals().getValue().getCatsReferralDetails().getCurrentStatusIsNotNull())
		{
			if( ReferralApptStatus.TRANSFERRED.equals(form.cmbReferrals().getValue().getCatsReferralDetails().getCurrentStatus().getReferralStatus()))
				isCatsTransferred = true;
		}
		
		
		
		boolean journeySelected = form.cmbPatientJourney().getValue() != null;
		boolean canAddEditBreachReasons = engine.hasRight(AppRight.CAN_RECORD_OVERALL_PATHWAY_BREACH_REASON);
		boolean hasBreachReasons = false;
		
		form.cmbPatientJourney().setEnabled(referralSelected);		
		form.btnView().setEnabled(journeySelected);
		form.btnAllComments().setEnabled(journeySelected);
		if (!journeySelected) 
		{ 
			form.btnAllComments().setTooltip(null);
			form.btnSetCancerPathway().setEnabled(false);
			form.btnSetCancerPathway().setText("Set Cancer Pathway");
		}
		
		if (referralSelected && journeySelected)
		{			
			form.btnAllComments().setEnabled(true);
			PatientJourneyDummyVo value = (PatientJourneyDummyVo) form.cmbPatientJourney().getValue();

			if (value != null &&
					value.getPatientJourneyIDIsNotNull())
			{			
				PatientPathwayJourneyRefVo refVo = new PatientPathwayJourneyRefVo();
				refVo.setID_PatientPathwayJourney(value.getPatientJourneyID());
				PatientJourneyCommentsVo  vo = domain.getPatientPathwayJourney(refVo);
				form.getGlobalContext().Pathways.setPatientJourneyComments(vo);
				
				hasBreachReasons = vo != null && vo.getPatientJourneyBreachReason() != null && vo.getPatientJourneyBreachReason().size() > 0;

				if (vo != null)
				{
					if (vo.getLinkedComments() == null || vo.getLinkedComments().size() ==0)
					{
						form.btnAllComments().setTooltip("<b>No Comments Recorded for the Selected Pathway</b>"); //WDEV-19603
//						form.btnAllComments().setEnabledImage(form.getImages().Core.NoComments24x24); //WDEV-19603
					}
					else

					{
						String tooltip = buildCommentsDisplayTooltip(vo);
						form.btnAllComments().setTooltip(tooltip.toString());
//						form.btnAllComments().setEnabledImage(form.getImages().Core.Comments24x24); //WDEV-19603
					}

					// WDEV-18474 set the CancerPathway button disabled if already set and set tooltip
					if (vo.getIsCancerPathwayIsNotNull() && vo.getIsCancerPathway())
					{
						form.btnSetCancerPathway().setEnabled(false);
						form.btnSetCancerPathway().setTooltip("Cancer Pathway Date " + vo.getCancerPathwayDate());
						form.btnSetCancerPathway().setText("Cancer Pathway " + vo.getCancerPathwayDate());
					}
					else 
					{
						form.btnSetCancerPathway().setEnabled(form.getGlobalContext().Pathways.getSelectedPatientPathwayJourney() != null && !isCatsTransferred); //WDEV-18520,wdev-20782
					}
				}	
				
				// start WDEV-20385
				PatientJourneyBreachReasonListVo breachReasons = domain.getBreachReasons(refVo);
				if(breachReasons == null)
				{
					form.btnViewBreach().setTooltip("<b>No Breach Reasons recorded.</b>");
				}
				else
				{
					String tooltipBreachReason = buildBreachReasonTooltip(breachReasons);
					form.btnViewBreach().setTooltip(tooltipBreachReason.toString());
				}
				// end WDEV-20385
			}		
		}
		
		
		// WDEV-18387 
		form.txtRttCurrentStatus().setEnabled(false);
		if (form.getLocalContext().getbDisplayRttStatusDetailsFieldIsNotNull() && 
				form.getLocalContext().getbDisplayRttStatusDetailsField())
		{		
			form.txtRttCurrentStatus().setVisible(true);
			form.lblRTTCurrentStatus().setVisible(true);	
		}
		else
		{
			form.txtRttCurrentStatus().setVisible(false);
			form.lblRTTCurrentStatus().setVisible(false);
		}
		
		if(!referralSelected)
		{
			form.lblRTTBreachDate().setVisible(false);
			form.txtRTTBreachDate().setVisible(false);
		}
		
		//WDEV-19604 
		form.txtNextValidationdate().setEnabled(false);
		form.btnValidate().setEnabled(referralSelected && journeySelected && !isCatsTransferred);	//wdev-20782
		
		//WDEV-19849 
		form.btnNewBreach().setEnabled(referralSelected && journeySelected && !isCatsTransferred);	//wdev-20782
		form.btnNewBreach().setVisible(canAddEditBreachReasons);
		
		form.btnViewBreach().setEnabled(referralSelected && journeySelected && hasAtLeastOneActiveBreachReason((PatientJourneyDummyVo) form.cmbPatientJourney().getValue()) && !isCatsTransferred);	//wdev-20782
		form.btnViewBreach().setVisible(hasBreachReasons);
		form.patientJourney().hideAllCMExceptViewClockHistory(isCatsTransferred);	//wdev-20782
	}

	private boolean hasAtLeastOneActiveBreachReason(PatientJourneyDummyVo journeySelected)
	{
		if (journeySelected != null)
			return domain.getHasAtLeastOneActiveBreachReason(journeySelected.getPatientJourneyID());
		
		return false;
	}

	private String buildCommentsDisplayTooltip(PatientJourneyCommentsVo vo)
	{
		StringBuffer tooltip = new StringBuffer();
		PatientJourneyCommentLiteVoCollection commentsList = vo.getLinkedComments().sort(PatientJourneyCommentLiteVo.getRecordingDateTimeComparator(SortOrder.DESCENDING));
		
		for (int i = 0; i < commentsList.size(); i++)
		{
			PatientJourneyCommentLiteVo commentVo = commentsList.get(i);

			if (commentVo == null)
				continue;
			
			tooltip.append((commentVo.getRecordingInfoIsNotNull() ?  (commentVo.getRecordingInfo().getRecordingUser() != null ? "Recording Information: <b>" + commentVo.getRecordingInfo().getRecordingUser().getIMosName() : "" )+ (commentVo.getRecordingInfo().getRecordingDateTime() != null ? ", " + commentVo.getRecordingInfo().getRecordingDateTime().toString()  + " </b><br/>" :""):"") + (commentVo.getCommentLevelIsNotNull() ? "Comment Level: " + "<b>" + commentVo.getCommentLevel().getText() + "</b>" : "") + "</b>" 
					  + (commentVo.getCommentIsNotNull() ? "<br/>Comment: <b>"  + formatTooltip(commentVo.getComment()) + "</b>":""));
			break;
		}
	
		
		return tooltip.toString();
	}
	
	
	//start WDEV-20385
	private String buildBreachReasonTooltip(PatientJourneyBreachReasonListVo commentVo)
	{
		StringBuilder tooltip = new StringBuilder();

		if (commentVo != null)
		{
			String separator = "";
			
			if (commentVo.getBreachReasonRecordingMOS() != null && commentVo.getBreachReasonRecordingMOS().getIMosName() != null)
			{
				tooltip.append("Authoring Information: <b>").append(commentVo.getBreachReasonRecordingMOS().getIMosName()).append("</b>");
				separator = ", ";
			}
			
			if (commentVo.getBreachReasonDate() != null)
			{
				tooltip.append("<b>").append(separator).append(commentVo.getBreachReasonDate().toString()).append("</b>");
				separator = "<br/>";
			}
			
			if (!separator.equals(""))
			{
				separator = "<br/>";
			}
			
			if (commentVo.getBreachReason() != null)
			{
				tooltip.append(separator).append("Breach Reason: <b>").append(commentVo.getBreachReason().toString()).append("</b>");
				separator = "<br/>";
			}
			
			if (commentVo.getBreachReasonComment() != null)
			{
				tooltip.append(separator).append("Breach Notes: <b>").append(formatTooltip(commentVo.getBreachReasonComment())).append("</b>");
			}
			
			if (Boolean.TRUE.equals(commentVo.getCorrected()))
			{
				if(commentVo.getCorrectionAuthoringInfo() != null && commentVo.getCorrectionAuthoringInfo().getRecordingUser() != null && commentVo.getCorrectionAuthoringInfo().getRecordingUser().getIMosName() != null)
				{
					tooltip.append(separator).append("Corrected By: <b>").append(commentVo.getCorrectionAuthoringInfo().getRecordingUser().getIMosName()).append("</b>");
					separator = ", ";
				}
				
				if (commentVo.getCorrectionAuthoringInfo() != null && commentVo.getCorrectionAuthoringInfo().getRecordingDateTime() != null)
				{
					tooltip.append("<b>").append(separator).append(commentVo.getCorrectionAuthoringInfo().getRecordingDateTime().toString()).append("</b>");
					separator = "<br/>";
				}
				
				if (!separator.equals(""))
				{
					separator = "<br/>";
				}
				
				if (commentVo.getCorrectionComments() != null)
				{
					tooltip.append(separator).append("Correction Comments: <b>").append(commentVo.getCorrectionComments().toString()).append("</b>");
				}
			}
		}
				
		return tooltip.toString();
	}
	//end WDEV-20385
	
	private String formatTooltip(String text) //WDEV-19603
	{
		if (text == null)
			return "";
		int len = 90;
		int textLength = text.length();

		if (text.length() < len)
			return text;

		StringBuilder str = new StringBuilder();

		while (textLength >= len)
		{	
			int spaceIndex = text.indexOf(" ",len)+1;
			
			if (text.charAt(len) == ' ')
			{
				str.append(text.substring(0, len) + "\n");				
			}	
			else if (spaceIndex > len)
			{				
				str.append(text.substring(0,spaceIndex != -1  && spaceIndex > len ? spaceIndex : len) + "\n");
						
			}
			text = text.substring(spaceIndex != -1 && spaceIndex > len?  spaceIndex : len);	
			textLength = text.length();
		}
		
		str.append(text);
		return str.toString();
	}

	private void viewSelectedJourney()
	{		

		//WDEV-21111
//		Object value = form.cmbPatientJourney().getValue();
		Object value = null;
		if (form.cmbPatientJourney() != null
				&& form.cmbPatientJourney().getValue() != null)
		{
			value = form.cmbPatientJourney().getValue();
		}
		else
		{
			return;
		} //WDEV-21111
		
		if(value == null)
			throw new CodingRuntimeException("No Journey Selected");
		
		PatientJourneyInterfaceVo patJourney = null;
		
		if (value instanceof PatwayHistoryDummyVo)
		{
			PatientPathwayJourneyRefVo vo = new PatientPathwayJourneyRefVo();
			PathwayLiteVo voPathway = new PathwayLiteVo();
			voPathway.setID_Pathway(((PatwayHistoryDummyVo)value).getPathwayHistoryID());
			vo.setID_PatientPathwayJourney(((PatientJourneyDummyVo)value).getPatientJourneyID());
			patJourney = domain.getPatientJourney(vo,voPathway);
		}
		else if (value instanceof PatientJourneyDummyVo)
		{
			PatientPathwayJourneyRefVo vo = new PatientPathwayJourneyRefVo();
			vo.setID_PatientPathwayJourney(((PatientJourneyDummyVo)value).getPatientJourneyID());
			patJourney = domain.getPatientJourney(vo, null);
		}
		PatientJourneyEventInterfaceVoCollection events = new PatientJourneyEventInterfaceVoCollection();		
		PatientJourneyEventInterfaceVoCollection allEvents = (PatientJourneyEventInterfaceVoCollection) patJourney.getJourneyEvents().clone();
		
		//Manage virtual events
		if (patJourney.getJourneyEventsIsNotNull())
		{
			for (int i = 0; i < allEvents.size(); i++)
			{
				PatientJourneyEventInterfaceVo event = allEvents.get(i);
				event.setClinicName(domain.getClinicName(event.getClinicCode()));
				if (event != null &&
						event.getIPatientJourneyEventStatus() != null &&
							event.getIPatientJourneyEventStatus().equals(EventStatus.ACTIVE) &&
								event.getIPatientJourneyEventScheduledDateTime() != null &&
									!event.getIPatientJourneyEventScheduledDateTime().equals(event.getIPatientJourneyEventDateTime()))
				{			
					PatientJourneyEventInterfaceVo virtual = (PatientJourneyEventInterfaceVo) event.clone();
					virtual.setID_PatientEvent(event.getBoId());
					virtual.setEventDateTime(event.getScheduledDate());
					virtual.setScheduledDate(event.getEventDateTime());
					virtual.setIsVirtual(Boolean.TRUE);
					virtual.setClinicName(event.getClinicName());					
					events.add(virtual);
					
					if(ConfigFlag.GEN.SHOW_VIRTUAL_EVENT_ONLY.getValue()) {
						patJourney.getJourneyEvents().remove(event);
					}
					
					event.setIsVirtual(Boolean.FALSE);
				}
				else
				{
					event.setIsVirtual(Boolean.FALSE);
				}								
			}
			
			for (int i = 0; i < events.size(); i++) 
			{
				patJourney.getJourneyEvents().add(events.get(i));
			}			
		}
		
		form.txtNextValidationdate().setValue(patJourney.getNextValidationDateIsNotNull() ? patJourney.getNextValidationDate().toString() : null); //WDEV-19604 
		form.txtLastValidation().setValue(patJourney.getLastValidationDateIsNotNull()? patJourney.getLastValidationDate().toString(): null);//WDEV-22775
		form.patientJourney().setValue(patJourney);		
		form.getGlobalContext().Pathways.setSelectedPatientPathwayJourney(patJourney);
		form.getGlobalContext().Pathways.setPatientJourneyCommentUpdated(patJourney);
		form.getGlobalContext().Pathways.setSelectedPathway((PathwayRefVo)patJourney.getPathway());
		form.getGlobalContext().Pathways.setSelectedPatientJourneyTargets(patJourney.getPathwayTargets());
		
		form.getGlobalContext().Pathways.setPatientJourneySearchCriteria(getSearchCriteria()); //WDEV-19389  
		
		updateControlsState();
	}
	
	public class AchievedDateComparator implements Comparator<Object>
	{
		public int compare(Object o1, Object o2)
		{
			DateTime achievedDate1 = null;
			DateTime achievedDate2 = null;
			
			if(o1 instanceof IPatientJourneyTarget)
			{
				IPatientJourneyTarget obj1 = ((IPatientJourneyTarget)o1);
				achievedDate1 = obj1.getIPatientJourneyTargetAchievedDate() != null ? obj1.getIPatientJourneyTargetAchievedDate() : null;
				IPatientJourneyTarget obj2 = ((IPatientJourneyTarget)o2);
				achievedDate2 = obj2.getIPatientJourneyTargetAchievedDate() != null ? obj2.getIPatientJourneyTargetAchievedDate() : null;
			}
			
			if(o1 instanceof IPatientJourneyEvent)
			{
				IPatientJourneyEvent obj1 = ((IPatientJourneyEvent)o1);			
				achievedDate1 = obj1.getIPatientJourneyEventDateTime() != null ? obj1.getIPatientJourneyEventDateTime() : null;
				IPatientJourneyEvent obj2 = ((IPatientJourneyEvent)o2);
				achievedDate2 = obj2.getIPatientJourneyEventDateTime() != null ? obj2.getIPatientJourneyEventDateTime() : null;
			}			
			
			if(achievedDate1 != null)
				return achievedDate1.compareTo(achievedDate2);
			 
			if(achievedDate2 != null)
				return achievedDate2.compareTo(achievedDate1);
						
			return 0;
		}
	}
	
	@Override
	protected void onPatientJourneyValueChanged() throws PresentationLogicException 
	{
		if (form.patientJourney().getLastAction() == null)
			return;
		if (form.patientJourney().getLastAction().equals(PatientJourneyAction.ADDEVENTTOTARGET))
		{
			//create new event form requires patientjourneytargetvo
			if(form.patientJourney().getSelectedJourneyTarget() instanceof PatientJourneyTargetInterfaceVo)
				form.getGlobalContext().Pathways.setSelectedPatientJourneyTarget(domain.getPatientJourneyTarget((PatientJourneyTargetInterfaceVo) form.patientJourney().getSelectedJourneyTarget()));
			
			engine.open(form.getForms().Pathways.CreateNewEvent);
		}
		else if (form.patientJourney().getLastAction().equals(PatientJourneyAction.CREATENEWEVENT))
		{
			//make sure following is set and clear setSelectedPatientJourneyTarget gc
		/*	form.getGlobalContext().Pathways.getPatientJourneySelectedPathwayPathway()*/

			PatientPathwayJourneyRefVo vo = new PatientJourneyShortVo();
			if (form.cmbPatientJourney().getValue() instanceof PatientJourneyDummyVo)
			{
				vo.setID_PatientPathwayJourney(((PatientJourneyDummyVo)form.cmbPatientJourney().getValue()).getPatientJourneyID());
			}
			else if (form.cmbPatientJourney().getValue() instanceof PatwayHistoryDummyVo)
			{
				vo.setID_PatientPathwayJourney(((PatwayHistoryDummyVo)form.cmbPatientJourney().getValue()).getPatientJourneyID());
			}
			
			form.getGlobalContext().Pathways.setSelectedPatientPathwayJourney(vo);
			form.getGlobalContext().Pathways.setSelectedPatientJourneyTarget(null);
			engine.open(form.getForms().Pathways.CreateNewEvent);
			
		}
		else if (form.patientJourney().getLastAction().equals(PatientJourneyAction.CREATENEWPATHWAY))
		{
			PatientPathwayJourneyRefVo vo = new PatientJourneyShortVo();
			if (form.cmbPatientJourney().getValue() instanceof PatientJourneyDummyVo)
			{
				vo.setID_PatientPathwayJourney(((PatientJourneyDummyVo)form.cmbPatientJourney().getValue()).getPatientJourneyID());
			}
			else if (form.cmbPatientJourney().getValue() instanceof PatwayHistoryDummyVo)
			{
				vo.setID_PatientPathwayJourney(((PatwayHistoryDummyVo)form.cmbPatientJourney().getValue()).getPatientJourneyID());
			}
			
			form.getGlobalContext().Pathways.setSelectedPatientPathwayJourney(vo);
			
			engine.open(form.getForms().Pathways.CreateNewPathway);
			
		}
		else if (form.patientJourney().getLastAction().equals(PatientJourneyAction.VIEWCLOCKHISTORY))
		{
			PatientPathwayJourneyRefVo vo = new PatientJourneyShortVo();
			if (form.cmbPatientJourney().getValue() instanceof PatientJourneyDummyVo)
			{
				vo.setID_PatientPathwayJourney(((PatientJourneyDummyVo)form.cmbPatientJourney().getValue()).getPatientJourneyID());
			}
			else if (form.cmbPatientJourney().getValue() instanceof PatwayHistoryDummyVo)
			{
				vo.setID_PatientPathwayJourney(((PatwayHistoryDummyVo)form.cmbPatientJourney().getValue()).getPatientJourneyID());
			}
			
			form.getGlobalContext().Pathways.setSelectedPatientPathwayJourney(vo);
			engine.open(form.getForms().Pathways.PatientJourneyClock);
		}
		else if (form.patientJourney().getLastAction().equals(PatientJourneyAction.ADDREADJUSTMENT))
		{			
			PatientJourneyJourneyTargetInterfaceVo a = (PatientJourneyJourneyTargetInterfaceVo) form.patientJourney().getSelectedPatientJourneyEventTarget();
 			form.getLocalContext().setPatientJourneyTargetInterface(a);
			TargetReadjustmentVoCollection targetReadjustments = null;
			if (a != null)
				targetReadjustments = a.getReadjustments();			
			form.getGlobalContext().Pathways.setTargetReadjustments(targetReadjustments);
			form.getGlobalContext().Pathways.setTargetReadjustmentsAction(TargetReadjustmentsAction.ADDREADJUSTMENT);
			engine.open(form.getForms().Pathways.TargetReadjustment, true, true);			
		}
		else if (form.patientJourney().getLastAction().equals(PatientJourneyAction.EDITREADJUSTMENT))
		{			
			PatientJourneyJourneyTargetInterfaceVo a = (PatientJourneyJourneyTargetInterfaceVo) form.patientJourney().getSelectedPatientJourneyEventTarget();
			form.getLocalContext().setPatientJourneyTargetInterface(a);
			TargetReadjustmentVoCollection targetReadjustments = null;
			if (a != null)
				targetReadjustments = a.getReadjustments();
			form.getGlobalContext().Pathways.setTargetReadjustments(targetReadjustments);			
			form.getGlobalContext().Pathways.setTargetReadjustmentsAction(TargetReadjustmentsAction.EDITREADJUSTMENT);
			engine.open(form.getForms().Pathways.TargetReadjustment, true, true);			
		}
		//WDEV-19603
		else if (form.patientJourney().getLastAction().equals(PatientJourneyAction.ADDPATHWAYCOMMENT))
		{				
			PatientJourneyDummyVo value = (PatientJourneyDummyVo) form.cmbPatientJourney().getValue();
			PatientPathwayJourneyRefVo refVo = new PatientPathwayJourneyRefVo();
			refVo.setID_PatientPathwayJourney(value.getPatientJourneyID());
			form.getGlobalContext().Pathways.setSelectedPatientPathwayJourney(refVo);
			engine.open(form.getForms().Pathways.PatientJourneyComment, new Object[] {NEW_COMMENT_MODE, form.patientJourney().getLastAction(), null});			
		}
		else if (form.patientJourney().getLastAction().equals(PatientJourneyAction.ADDTARGETCOMMENT))
		{			
			IPatientJourneyTarget target = form.patientJourney().getSelectedPatientJourneyEventTarget();
			form.getGlobalContext().Pathways.setSelectedPatientJourneyTargetRef((PatientJourneyTargetRefVo) target);
			engine.open(form.getForms().Pathways.PatientJourneyComment, new Object[] {NEW_COMMENT_MODE, form.patientJourney().getLastAction(), null});	
		}
		else if (form.patientJourney().getLastAction().equals(PatientJourneyAction.ADDEVENTCOMMENT))
		{	
			PatientJourneyEventInterfaceVo event = (PatientJourneyEventInterfaceVo) form.patientJourney().getSelectedEvent();
			engine.open(form.getForms().Pathways.PatientJourneyComment, new Object[] {NEW_COMMENT_MODE, form.patientJourney().getLastAction(), event});	
		}
		else if(PatientJourneyAction.RECORDBREACHREASON.equals(form.patientJourney().getLastAction()))
		{
			engine.open(form.getForms().Pathways.PatientJourneyBreachReason);
		}
	}
	@Override
	protected void onFormDialogClosed(FormName formName, DialogResult result) throws PresentationLogicException
	{
		if ((formName.equals(form.getForms().Pathways.CreateNewPathway)) && (result.equals(DialogResult.OK)))
		{
			cmbReferralValueChanged();
			PatientJourneyDummyVo voDummy = new PatientJourneyDummyVo();
			PatientPathwayJourneyRefVo current = form.getGlobalContext().Pathways.getSelectedPatientPathwayJourney();
			voDummy.setPatientJourneyID(current.getID_PatientPathwayJourney());
			form.cmbPatientJourney().setValue(voDummy);
			onBtnViewClick();
		}
		// WDEV-18474
		if ((formName.equals(form.getForms().Core.DateEntryDialog)) && (result.equals(DialogResult.OK)))
		{
			// Get the date that was recorded
			try 
			{
				domain.saveCancerPathway(form.getGlobalContext().Pathways.getSelectedPatientPathwayJourney(), form.getGlobalContext().Core.getGenericDate());
			} 
			catch (StaleObjectException e) 
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			form.btnSetCancerPathway().setEnabled(false);
			form.btnSetCancerPathway().setTooltip("Cancer Pathway - " + form.getGlobalContext().Core.getGenericDate());
			form.btnSetCancerPathway().setText("Cancer Pathway " + form.getGlobalContext().Core.getGenericDate());
		}
		if ((formName.equals(form.getForms().Pathways.CreateNewEvent)) && (result.equals(DialogResult.OK)))
		{
			cmbReferralValueChanged();
			PatientJourneyDummyVo voDummy = new PatientJourneyDummyVo();
			PatientPathwayJourneyRefVo current = form.getGlobalContext().Pathways.getSelectedPatientPathwayJourney();
			voDummy.setPatientJourneyID(current.getID_PatientPathwayJourney());
			form.cmbPatientJourney().setValue(voDummy);
			onBtnViewClick();
		}
		if ((formName.equals(form.getForms().Pathways.TargetReadjustment)) && (result.equals(DialogResult.OK)))
		{
			TargetReadjustmentVoCollection targetReadjustments = form.getGlobalContext().Pathways.getTargetReadjustments();
			PatientJourneyJourneyTargetInterfaceVo patientJourneyTarget = form.getLocalContext().getPatientJourneyTargetInterface();
			
			if (patientJourneyTarget == null)
				return;
			
			patientJourneyTarget.setReadjustments(targetReadjustments);
			patientJourneyTarget.setHasReadjustments(Boolean.TRUE);
			String[] errors = patientJourneyTarget.validate();
			if(errors != null && errors.length > 0)
			{
				engine.showErrors(errors);	
				return;
			}
			
			try 
			{				
				domain.save(patientJourneyTarget);
			} 
			catch (StaleObjectException e) 
			{			
				e.printStackTrace();				
			}
		}
		if(formName.equals(form.getForms().Pathways.PatientJourneyComment))//WDEV-21019
			loadPatientJourneys();
		
		updateControlsState();
		onBtnViewClick();
	}

	protected void onLnkReturnClick() throws PresentationLogicException
	{
		engine.open(form.getForms().Pathways.Worklist);
	}

	@Override
	protected void onLnkRetunToPathwayClick() throws PresentationLogicException
	{
		engine.open(form.getForms().Pathways.PatientPathwaysAwaitingValidationWorklist);
	}

//	protected void onBtnViewLastCommentClick() throws PresentationLogicException
//	{
//		engine.open(form.getForms().Pathways.PatientJourneyComment, new Object[] { VIEW_LAST_COMMENT_MODE, null, null});
//	}

	@Override
	protected void onBtnValidateClick() throws PresentationLogicException
	{
		engine.open(form.getForms().Pathways.PatientJourneyComment, new Object[] { VALIDATE_MODE, PatientJourneyAction.ADDPATHWAYCOMMENT, null});		
	}

	@Override
	protected void onBtnAllCommentsClick() throws PresentationLogicException
	{
		engine.open(form.getForms().Pathways.PatientJourneyComments);
	}

	@Override
	protected void onBtnViewBreachClick() throws PresentationLogicException
	{
		engine.open(form.getForms().Pathways.BreachReasonListDialog);	
	}

	@Override
	protected void onBtnNewBreachClick() throws PresentationLogicException
	{
		engine.open(form.getForms().Pathways.BreachReasonListDialog, new Object[] {PatientJourneyAction.RECORDBREACHREASON});			
	}	
}
