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

package ims.pathways.forms.patientjourneycomment;

import ims.configuration.gen.ConfigFlag;
import ims.core.vo.MemberOfStaffLiteVo;
import ims.core.vo.RecordingUserInformationVo;
import ims.core.vo.enums.PatientJourneyAction;
import ims.domain.exceptions.DomainInterfaceException;
import ims.domain.exceptions.StaleObjectException;
import ims.framework.FormName;
import ims.framework.enumerations.DialogResult;
import ims.framework.enumerations.FormMode;
import ims.framework.exceptions.PresentationLogicException;
import ims.framework.utils.Date;
import ims.framework.utils.DateTime;
import ims.pathways.forms.patientjourneycomment.GenForm.lyrCommentWizardLayer.tabPageDetailsContainer.GroupCommentTypesEnumeration;
import ims.pathways.forms.patientjourneycomment.GenForm.lyrCommentWizardLayer.tabPageDetailsContainer.grdEventsRow;
import ims.pathways.forms.patientjourneycomment.GenForm.lyrCommentWizardLayer.tabPageDetailsContainer.grdEventsRowCollection;
import ims.pathways.forms.patientjourneycomment.GenForm.lyrCommentWizardLayer.tabPageDetailsContainer.grdTargetsRow;
import ims.pathways.forms.patientjourneycomment.GenForm.lyrCommentWizardLayer.tabPageDetailsContainer.grdTargetsRowCollection;
import ims.pathways.vo.EventMinVo;
import ims.pathways.vo.PathwayLiteVo;
import ims.pathways.vo.PathwayRTTCurrentStatusVo;
import ims.pathways.vo.PathwayRTTCurrentStatusVoCollection;
import ims.pathways.vo.PatientEventForPathwayCommentsVo;
import ims.pathways.vo.PatientEventForPathwayCommentsVoCollection;
import ims.pathways.vo.PatientEventRefVo;
import ims.pathways.vo.PatientJourneyCommentVo;
import ims.pathways.vo.PatientJourneyEventInterfaceVo;
import ims.pathways.vo.PatientJourneyEventInterfaceVoCollection;
import ims.pathways.vo.PatientJourneyInterfaceVo;
import ims.pathways.vo.PatientJourneyJourneyTargetInterfaceVoCollection;
import ims.pathways.vo.PatientJourneyTargetForPathwayCommentsVo;
import ims.pathways.vo.PatientJourneyTargetForPathwayCommentsVoCollection;
import ims.pathways.vo.PatientJourneyTargetRefVo;
import ims.pathways.vo.PauseDetailsVo;
import ims.pathways.vo.PauseDetailsVoCollection;
import ims.pathways.vo.lookups.CommentLevel;
import ims.pathways.vo.lookups.EventStatus;

import java.util.ArrayList;

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_COMMENT_MODE = new Integer(4);
	
	@Override
	protected void onFormOpen(Object[] args) throws ims.framework.exceptions.PresentationLogicException
	{
		initialize(args);		
		open();
	}
	
	private void initialize(Object[] args)
	{		
		if (args != null)
		{
			if (args.length > 0 && args[0] != null)
			{				
				if (args[0] instanceof Integer)
					form.getLocalContext().setDialogFunctionMode((Integer) args[0]);
			}
			if (args.length > 1 && args[1] != null && args[1] instanceof PatientJourneyAction)
			{
				form.getLocalContext().setCommentType((PatientJourneyAction) args[1]);				
			}
			if (args.length > 2 && args[2] != null && args[2] instanceof PatientJourneyEventInterfaceVo)
			{
				form.getLocalContext().setPreSelectedEventRef((PatientJourneyEventInterfaceVo) args[2]);				
			}
		}	
		form.getLocalContext().setCurrentComment(null);
	}
	
	private void open()
	{
		PatientJourneyInterfaceVo journey = domain.getJourneyAndEvents(form.getGlobalContext().Pathways.getSelectedPatientPathwayJourney(), null);
		form.getLocalContext().setCurrentPathwayJourney(journey);
		
		
		FormMode mode = NEW_COMMENT_MODE.equals(form.getLocalContext().getDialogFunctionMode()) || VALIDATE_MODE.equals(form.getLocalContext().getDialogFunctionMode()) ? FormMode.EDIT : FormMode.VIEW;
		
		Boolean isValidateMode 		= VALIDATE_MODE.equals(form.getLocalContext().getDialogFunctionMode()) ? true : false;
		Boolean isViewCommentMode	= VIEW_COMMENT_MODE.equals(form.getLocalContext().getDialogFunctionMode()) ? true : false;
		Boolean isNewCommentMode	= NEW_COMMENT_MODE.equals(form.getLocalContext().getDialogFunctionMode()) ? true : false;
		
		if (isNewCommentMode)
		{
			form.getGlobalContext().Pathways.setPatientJourneySelectedComment(null);			
		}	
		
		form.getLocalContext().setCurrentComment(domain.getCommentDetails(form.getGlobalContext().Pathways.getPatientJourneySelectedComment()));
		populateScreenFromData(form.getLocalContext().getCurrentComment(),isNewCommentMode, isViewCommentMode, isValidateMode);
		
		form.setMode(mode);
	}
	
	@Override
	protected void onFormModeChanged()
	{
		updateControlsState();
	}
	
	private void updateControlsState()
	{
		setCommentsLabel(form.lyrCommentWizard().tabPageDetails().GroupCommentTypes().getValue());
		
		Boolean isNewCommentMode	= NEW_COMMENT_MODE.equals(form.getLocalContext().getDialogFunctionMode()) ? true : false;
	
		//Events grid
		Boolean displayEventGrid = form.getLocalContext().getCommentTypeIsNotNull() && PatientJourneyAction.ADDEVENTCOMMENT.equals(form.getLocalContext().getCommentType());
		form.lyrCommentWizard().tabPageDetails().lblEventHeader().setVisible(displayEventGrid);
		form.lyrCommentWizard().tabPageDetails().grdEvents().setVisible(displayEventGrid);
		form.lyrCommentWizard().tabPageDetails().grdEvents().setReadOnly(isNewCommentMode ? false : true);
		
		//Targets grid
		Boolean displayTargetGrid = form.getLocalContext().getCommentTypeIsNotNull() && PatientJourneyAction.ADDEVENTTOTARGET.equals(form.getLocalContext().getCommentType());
		form.lyrCommentWizard().tabPageDetails().lblTargetHeader().setVisible(displayTargetGrid);
		form.lyrCommentWizard().tabPageDetails().grdTargets().setVisible(displayTargetGrid);
		form.lyrCommentWizard().tabPageDetails().grdTargets().setReadOnly(isNewCommentMode ? false : true);
		
		if(FormMode.EDIT.equals(form.getMode()))
		{
			form.lyrCommentWizard().tabPageDetails().GroupCommentTypes().setEnabled(!VALIDATE_MODE.equals(form.getLocalContext().getDialogFunctionMode()));
			form.lyrCommentWizard().tabPageDetails().txtComments().setEnabled(FormMode.EDIT.equals(form.getMode()));
			form.lyrCommentWizard().tabPageDetails().txtComments().setRequired(!VALIDATE_MODE.equals(form.getLocalContext().getDialogFunctionMode()));//WDEV-20385
		}
		
		form.btnSave().setVisible(FormMode.EDIT.equals(form.getMode()));
		form.btnCancel().setVisible(FormMode.EDIT.equals(form.getMode()));
		form.btnClose().setVisible(FormMode.VIEW.equals(form.getMode()));
		
		//Comment Type radio buttons
		form.lyrCommentWizard().tabPageDetails().GroupCommentTypes().setEnabled(NEW_COMMENT_MODE.equals(form.getLocalContext().getDialogFunctionMode()));
		
		//RTT Status Details
		Boolean displayCurrentRTTStatus = Boolean.TRUE.equals(form.getLocalContext().getDisplayRttStatusDetailsField());
		form.lyrCommentWizard().tabPageDetails().txtRttCurrentStatus().setVisible(displayCurrentRTTStatus);
		form.lyrCommentWizard().tabPageDetails().txtRttCurrentStatus().setEnabled(false);
		form.lyrCommentWizard().tabPageDetails().lblRTTCurrentStatus().setVisible(displayCurrentRTTStatus);
		
		//Pathway Name Details
		form.lyrCommentWizard().tabPageDetails().txtPathwayName().setEnabled(false);
		
		//6.	When adding a validation comment a user must enter a validation date or reason as to why there is no more validation
		Boolean noNextValidationDate = FormMode.EDIT.equals(form.getMode()) && form.lyrCommentWizard().tabPageDetails().dteNextValidation().getValue() == null;
		form.lyrCommentWizard().tabPageDetails().txtReason().setEnabled(noNextValidationDate);
		form.lyrCommentWizard().tabPageDetails().cmbReason().setEnabled(noNextValidationDate);
		form.lyrCommentWizard().tabPageDetails().cmbReason().setRequired(noNextValidationDate);
		
		//Correct and RIE buttons
		form.btnRIE().setVisible(FormMode.VIEW.equals(form.getMode()) && form.getLocalContext().getCurrentCommentIsNotNull() && !Boolean.TRUE.equals(form.getLocalContext().getCurrentComment().getIsRIE()));
		form.btnCorrect().setVisible(FormMode.VIEW.equals(form.getMode()));
		form.btnCorrect().setEnabled(FormMode.VIEW.equals(form.getMode()) && form.getLocalContext().getCurrentCommentIsNotNull() && !Boolean.TRUE.equals(form.getLocalContext().getCurrentComment().getIsRIE()) && !Boolean.TRUE.equals(form.getLocalContext().getCurrentComment().getCorrected()));
		
		//correction details
		Boolean displayCorrection = form.getLocalContext().getCurrentCommentIsNotNull() && Boolean.TRUE.equals(form.getLocalContext().getCurrentComment().getCorrected());
		form.lyrCommentWizard().tabPageDetails().lblCorrection().setVisible(displayCorrection);
		form.lyrCommentWizard().tabPageDetails().txtCorrection().setVisible(displayCorrection);
		form.lyrCommentWizard().tabPageDetails().txtCorrection().setEnabled(false);	
		form.lyrCommentWizard().tabPageDetails().lblCorrectedBy().setVisible(displayCorrection);
		form.lyrCommentWizard().tabPageDetails().lblCorrectedTime().setVisible(displayCorrection);
		form.lyrCommentWizard().tabPageDetails().lblCorrectedByValue().setVisible(displayCorrection);
		form.lyrCommentWizard().tabPageDetails().lblCorrectedTimeValue().setVisible(displayCorrection);
	}
	
	private void setCommentsLabel(GroupCommentTypesEnumeration value)
	{
		if (value == null)
			return;
		form.lyrCommentWizard().tabPageDetails().lblComments().setValue("Comment for " + (GroupCommentTypesEnumeration.rdoEvent.equals(value) ? "Event" : (GroupCommentTypesEnumeration.rdoTarget.equals(value) ? "Target" : "Pathway")) + ":");
	}
	
	private void populateScreenFromData(PatientJourneyCommentVo currentComment, Boolean isNewCommentMode, Boolean isViewCommentMode, Boolean isValidateMode)
	{
		clearScreen();	
		setCommentType(currentComment, form.getLocalContext().getCommentType(), isNewCommentMode, isViewCommentMode, isValidateMode);	
		form.lyrCommentWizard().tabPageDetails().txtComments().setValue(currentComment != null ? currentComment.getComment() : null);
		populateRecordingInfoLabels(currentComment != null ? currentComment.getRecordingInfo() : getRecordingInfo());	
		form.lyrCommentWizard().tabPageDetails().dteNextValidation().setValue(isValidateMode ? null : form.getLocalContext().getCurrentPathwayJourney().getNextValidationDate());
		form.lyrCommentWizard().tabPageDetails().cmbReason().setValue(currentComment != null ? currentComment.getReasonNoValidation() : null);
		form.lyrCommentWizard().tabPageDetails().txtReason().setValue(currentComment != null ? currentComment.getReasonNoValidationDate()  : null);
		
		if (Boolean.TRUE.equals(ConfigFlag.DOM.RTT_STATUS_POINT_FUNCTIONALITY.getValue()) && form.getLocalContext().getCurrentPathwayJourneyIsNotNull() && form.getLocalContext().getCurrentPathwayJourney().getCurrentClockIsNotNull() && form.getLocalContext().getCurrentPathwayJourney().getCurrentClock().getRTTStatusHistoryIsNotNull() && form.getLocalContext().getCurrentPathwayJourney().getCurrentClock().getCurrentRTTStatusIsNotNull())
		{
			populateRTTStatus(form.getLocalContext().getCurrentPathwayJourney().getCurrentClock().getCurrentRTTStatus(), form.getLocalContext().getCurrentPathwayJourney().getCurrentClock().getRTTStatusHistory()); 
		}
		
		form.lyrCommentWizard().tabPageDetails().txtPathwayName().setValue(form.getLocalContext().getCurrentPathwayJourneyIsNotNull() &&  form.getLocalContext().getCurrentPathwayJourney().getPathwayIsNotNull() ? form.getLocalContext().getCurrentPathwayJourney().getPathway().getName() : " ");		
		populateRTTBreachDate(form.getLocalContext().getCurrentPathwayJourney());
		
		Boolean displayCorrection = form.getLocalContext().getCurrentCommentIsNotNull() && Boolean.TRUE.equals(form.getLocalContext().getCurrentComment().getCorrected());	
		if (displayCorrection)
		{
			String hcp = currentComment != null && currentComment.getCorrectedAuthoringInformationIsNotNull() && currentComment.getCorrectedAuthoringInformation().getAuthoringHcpIsNotNull() ? currentComment.getCorrectedAuthoringInformation().getAuthoringHcp().getIHcpName() : " ";
			form.lyrCommentWizard().tabPageDetails().lblCorrectedByValue().setValue(hcp != null && hcp.length() > 30 ? hcp.substring(0, 30) : hcp);
			form.lyrCommentWizard().tabPageDetails().lblCorrectedTimeValue().setValue(currentComment != null && currentComment.getCorrectedAuthoringInformationIsNotNull() && currentComment.getCorrectedAuthoringInformation().getAuthoringDateTimeIsNotNull() ? currentComment.getCorrectedAuthoringInformation().getAuthoringDateTime().toString() : " ");
			form.lyrCommentWizard().tabPageDetails().txtCorrection().setValue(currentComment.getCorrectionComments());
		}
	}
	
	private void populateRTTBreachDate(PatientJourneyInterfaceVo patientJourneyInterfaceVo)
	{
		Date breachDate = domain.getRTTBreachDate(patientJourneyInterfaceVo);
		
		form.lyrCommentWizard().tabPageDetails().lblRTTBreachDate().setVisible(breachDate != null);
		form.lyrCommentWizard().tabPageDetails().txtRTTBreachDate().setEnabled(false);
		form.lyrCommentWizard().tabPageDetails().txtRTTBreachDate().setVisible(breachDate != null);
		form.lyrCommentWizard().tabPageDetails().txtRTTBreachDate().setValue(breachDate != null ? breachDate.toString() : null);
		
		int nrOfDays = 0; 
		if (patientJourneyInterfaceVo != null && patientJourneyInterfaceVo.getCurrentClockIsNotNull() && patientJourneyInterfaceVo.getCurrentClock().getPauseDetailsIsNotNull())
			nrOfDays = populateAdjustedRTTBreachDate(patientJourneyInterfaceVo.getCurrentClock().getPauseDetails());
		
		form.lyrCommentWizard().tabPageDetails().lblAdjusted().setVisible(form.lyrCommentWizard().tabPageDetails().txtRTTBreachDate().isVisible() && nrOfDays != 0);
		form.lyrCommentWizard().tabPageDetails().txtAdjustedDate().setEnabled(false);
		form.lyrCommentWizard().tabPageDetails().txtAdjustedDate().setVisible(form.lyrCommentWizard().tabPageDetails().txtRTTBreachDate().isVisible() && nrOfDays != 0);
		form.lyrCommentWizard().tabPageDetails().txtAdjustedDate().setValue(form.lyrCommentWizard().tabPageDetails().txtRTTBreachDate().isVisible() && nrOfDays != 0 && breachDate != null ? breachDate.addDay(nrOfDays).toString() : null);
	}
	
	private int populateAdjustedRTTBreachDate(PauseDetailsVoCollection pauseDetailsColl)
	{	
		int nrOfDays = 0;
		if (pauseDetailsColl != null && pauseDetailsColl.size() > 0 && pauseDetailsColl.get(0) != null )
		{
			if (pauseDetailsColl != null && pauseDetailsColl.size() > 0)
			{
				for (int i = 0; i < pauseDetailsColl.size(); i++)
				{	
					PauseDetailsVo pauseDet = pauseDetailsColl.get(i);
					if (pauseDet.getActive() && pauseDet.getPauseStartIsNotNull() && pauseDet.getPauseStopIsNotNull() && pauseDet.getPauseStart().isLessThan(pauseDet.getPauseStop()))
						nrOfDays = nrOfDays + (int) Date.daysBetween(pauseDet.getPauseStart(), pauseDet.getPauseStop());
				}

			}
		}
		
		return nrOfDays;	
	}

	private void populateRTTStatus(PathwayRTTCurrentStatusVo pathwayRTTCurrentStatusVo, PathwayRTTCurrentStatusVoCollection rttStatusHistory)
	{
		form.lyrCommentWizard().tabPageDetails().txtRttCurrentStatus().setValue(null);
		form.lyrCommentWizard().tabPageDetails().txtRttCurrentStatus().setTooltip(" ");
		form.getLocalContext().setDisplayRttStatusDetailsField(false);
					
		if (pathwayRTTCurrentStatusVo != null && rttStatusHistory != null && rttStatusHistory.size() > 0)
		{
			if (rttStatusHistory.get(0) != null)
				form.lyrCommentWizard().tabPageDetails().txtRttCurrentStatus().setValue(rttStatusHistory.get(0).getRTTStatus().getNationalCodeIsNotNull() ?  rttStatusHistory.get(0).getRTTStatus().getNationalCode().toString() + ". " + rttStatusHistory.get(0).getRTTStatus().getDescription() : rttStatusHistory.get(0).getRTTStatus().getDescription());
			String rttHistoryTooltip = formatRTTStatusHistoryTooltip(true, rttStatusHistory.get(0));
			
    		if ( rttStatusHistory.size() > 1)
    		{
    			rttHistoryTooltip += "RTT Status History: <br>";
    			for (int i = 1; i < rttStatusHistory.size(); i++)
    			{    				
    				rttHistoryTooltip += formatRTTStatusHistoryTooltip(false, rttStatusHistory.get(i));
    			}					
    		}
    		
    		form.lyrCommentWizard().tabPageDetails().txtRttCurrentStatus().setTooltip(rttHistoryTooltip);
    		form.getLocalContext().setDisplayRttStatusDetailsField(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 CommentLevel getCommentLevelFromScreenOption(GroupCommentTypesEnumeration onScreenValue)
	{
		if (GroupCommentTypesEnumeration.rdoPathway.equals(onScreenValue))
			return CommentLevel.PATHWAY;
		else if (GroupCommentTypesEnumeration.rdoEvent.equals(onScreenValue))
			return CommentLevel.EVENT;
		if (GroupCommentTypesEnumeration.rdoTarget.equals(onScreenValue))
			return CommentLevel.TARGET;
		return null;
	}
		
	private String[] validateUI()
	{
		ArrayList<String> errors = new ArrayList<String>();
		
		if (form.lyrCommentWizard().tabPageDetails().dteNextValidation().getValue() != null && form.lyrCommentWizard().tabPageDetails().dteNextValidation().getValue().isLessOrEqualThan(new Date()))
		{
			errors.add("'Next Validation Date' must be a future date.");				
		}

		if (GroupCommentTypesEnumeration.rdoEvent.equals(form.lyrCommentWizard().tabPageDetails().GroupCommentTypes().getValue()) && form.getLocalContext().getPreSelectedEventRef() == null)
		{
			errors.add("Event selection is mandatory when 'Event Comment' was selected.");				
		}

		if (GroupCommentTypesEnumeration.rdoTarget.equals(form.lyrCommentWizard().tabPageDetails().GroupCommentTypes().getValue())  && form.getLocalContext().getPreSelectedTargetRef() == null)
		{
			errors.add("Target selection is mandatory when 'Target Comment' was selected.");				
		}

		if (form.lyrCommentWizard().tabPageDetails().cmbReason().isRequired() && form.lyrCommentWizard().tabPageDetails().cmbReason().getValue() == null)
		{
			errors.add("'Reason for No Validation Date' is mandatory.");				
		}
		if(form.lyrCommentWizard().tabPageDetails().dteNextValidation().getValue() != null && form.getLocalContext().getCurrentPathwayJourneyIsNotNull() && form.lyrCommentWizard().tabPageDetails().dteNextValidation().getValue().isLessOrEqualThan(form.getLocalContext().getCurrentPathwayJourney().getNextValidationDate()))
			errors.add("The Next Validation Date should be greater than the Last Validation Date.");
		
		//WDEV-20385
		if(!VALIDATE_MODE.equals(form.getLocalContext().getDialogFunctionMode()) && form.lyrCommentWizard().tabPageDetails().txtComments().getValue() == null)
		{
			errors.add("Comment is mandatory.");
		}

		if (errors.size() == 0)
			return null;
		
		return errors.toArray(new String[errors.size()]); 
	}

	@Override
	protected void onBtnCancelClick() throws ims.framework.exceptions.PresentationLogicException
	{
		engine.close(DialogResult.CANCEL);
	}
	
	private void populateEvents(PatientJourneyInterfaceVo selectedPatientPathwayJourney, PatientEventRefVo preSelectedEventRef)
	{
		if (selectedPatientPathwayJourney == null)
			return;
		
		PatientEventForPathwayCommentsVoCollection events = processVirtualEvents(selectedPatientPathwayJourney, preSelectedEventRef);
		populateEventsGrid(events);

	}
	private void clearScreen()
	{
		form.lyrCommentWizard().tabPageDetails().dteNextValidation().setValue(null);
		form.lyrCommentWizard().tabPageDetails().txtComments().setValue(null);
		form.lyrCommentWizard().tabPageDetails().txtReason().setValue(null);
		form.lyrCommentWizard().tabPageDetails().txtCorrection().setValue(null);
		form.lyrCommentWizard().tabPageDetails().cmbReason().setValue(null);	
	}
	
	private void populateEventsGrid(PatientEventForPathwayCommentsVoCollection events)
	{
		form.lyrCommentWizard().tabPageDetails().grdEvents().getRows().clear();
		
		if (events == null)
			return;	

		for (int i=0; i< events.size(); i++)
		{	
			if (events.get(i) == null)
				continue;
			grdEventsRow eventRow = form.lyrCommentWizard().tabPageDetails().grdEvents().getRows().newRow();
			eventRow.setColEvent(events.get(i).getEvent().getName());
			eventRow.setColSelect(Boolean.TRUE.equals(events.get(i).getDisplayTicked()) ? Boolean.TRUE : Boolean.FALSE);
			eventRow.setColSelectReadOnly(false);
			
			eventRow.setValue(events.get(i));
		}
	}
		
	private PatientEventForPathwayCommentsVoCollection processVirtualEvents(PatientJourneyInterfaceVo journey, ims.pathways.vo.PatientEventRefVo preSelectedEventRef)
	{
		if (journey == null || journey.getJourneyEvents() == null || journey.getJourneyEvents().size() == 0)
			return null;

		PatientJourneyEventInterfaceVoCollection allEvents = (PatientJourneyEventInterfaceVoCollection) journey.getJourneyEvents().clone();
		PatientJourneyEventInterfaceVoCollection processedEvents = new PatientJourneyEventInterfaceVoCollection();

		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());					
				processedEvents.add(virtual);

				if(ConfigFlag.GEN.SHOW_VIRTUAL_EVENT_ONLY.getValue()) {
					journey.getJourneyEvents().remove(event);
				}

				event.setIsVirtual(Boolean.FALSE);
			}
			else
			{
				event.setIsVirtual(Boolean.FALSE);
			}								
		}

		for (int i = 0; i < processedEvents.size(); i++) 
		{
			journey.getJourneyEvents().add(processedEvents.get(i));
		}

		PatientEventForPathwayCommentsVoCollection displayEvents = formatEventsForDisplay(journey.getJourneyEvents(), preSelectedEventRef);

		return displayEvents;
	}
	private PatientEventForPathwayCommentsVoCollection formatEventsForDisplay(PatientJourneyEventInterfaceVoCollection journeyEventsColl, ims.pathways.vo.PatientEventRefVo preSelectedEventRef)
	{
		PatientEventForPathwayCommentsVoCollection displayEvents = new PatientEventForPathwayCommentsVoCollection();
		
		for (int k = 0; k< journeyEventsColl.size(); k++)
		{
			if (journeyEventsColl.get(k) == null)
				continue;

			PatientEventForPathwayCommentsVo eventVo = new PatientEventForPathwayCommentsVo();
			eventVo.setID_PatientEvent(journeyEventsColl.get(k).getID_PatientEvent());
			eventVo.setDescription(journeyEventsColl.get(k).getDescription());
			eventVo.setEventDateTime(journeyEventsColl.get(k).getEventDateTime());

			EventMinVo eventMinVo = new EventMinVo();
			eventMinVo.setID_Event(journeyEventsColl.get(k).getEvent().getID_Event());
			eventMinVo.setName(journeyEventsColl.get(k).getEvent().getName());
			eventMinVo.setEventType(journeyEventsColl.get(k).getEvent().getEventType());
			eventMinVo.setStatus(journeyEventsColl.get(k).getEvent().getStatus());

			eventVo.setEvent(eventMinVo);

			if (preSelectedEventRef != null && preSelectedEventRef.getID_PatientEvent().equals(eventVo.getID_PatientEvent()))
				eventVo.setDisplayTicked(Boolean.TRUE);

			displayEvents.add(eventVo);
		}
		if (displayEvents.size() == 0)
			return null;

		return displayEvents;				
	}

	private PatientJourneyCommentVo populateDataFromScreen(PatientJourneyInterfaceVo record, PatientJourneyCommentVo currentComment)
	{
		if (record == null)
			return null;
		if (currentComment == null)					
			currentComment = new PatientJourneyCommentVo();
		else 
			currentComment = (PatientJourneyCommentVo) form.getLocalContext().getCurrentComment().clone();
		
		currentComment.setCommentLevel(getCommentLevelFromScreenOption(form.lyrCommentWizard().tabPageDetails().GroupCommentTypes().getValue()));
		currentComment.setComment(form.lyrCommentWizard().tabPageDetails().txtComments().getValue());
		currentComment.setRecordingInfo(getRecordingInfo());
		currentComment.setLinkedEvent(form.getLocalContext().getPreSelectedEventRef());
		currentComment.setLinkedTarget(form.getLocalContext().getPreSelectedTargetRef());
		currentComment.setReasonNoValidation(form.lyrCommentWizard().tabPageDetails().cmbReason().getValue());
		currentComment.setReasonNoValidationDate(form.lyrCommentWizard().tabPageDetails().txtReason().getValue());
		
		return currentComment;	
	}
	
	private RecordingUserInformationVo getRecordingInfo()
	{
		Object currentLoggedInUser = domain.getMosUser();
		if (currentLoggedInUser == null || !(currentLoggedInUser instanceof MemberOfStaffLiteVo))
			return null;	
		RecordingUserInformationVo recInfoVo = new RecordingUserInformationVo();
		recInfoVo.setRecordingUser((MemberOfStaffLiteVo) currentLoggedInUser);
		recInfoVo.setRecordingDateTime(new DateTime());
		
		return recInfoVo;
	}
	
	private void populateRecordingInfoLabels(RecordingUserInformationVo recInfoVo)
	{
		if (recInfoVo == null)
			return;
		
		String hcp = recInfoVo.getRecordingUser() != null ? recInfoVo.getRecordingUser().getIMosName() : " ";
		form.lyrCommentWizard().tabPageDetails().lblRecordedByValue().setValue(hcp != null && hcp.length() > 30 ? hcp.substring(0, 30) : hcp);
		form.lyrCommentWizard().tabPageDetails().lblRecordedByValue().setTooltip(hcp);

		form.lyrCommentWizard().tabPageDetails().lblRecDateTimValue().setValue(recInfoVo.getRecordingDateTime() != null ? recInfoVo.getRecordingDateTime().toString() : " ");
	}
	
	private PatientJourneyTargetForPathwayCommentsVoCollection formatTargetsForDisplay(PatientJourneyJourneyTargetInterfaceVoCollection targets, PatientJourneyTargetRefVo patientJourneyTargetRefVo)
	{
		PatientJourneyTargetForPathwayCommentsVoCollection dispTargets = new PatientJourneyTargetForPathwayCommentsVoCollection();
		
		for (int k = 0; k< targets.size(); k++)
		{
			if (targets.get(k) == null)
				continue;

			PatientJourneyTargetForPathwayCommentsVo targetVo = new PatientJourneyTargetForPathwayCommentsVo();
			targetVo.setID_PatientJourneyTarget(targets.get(k).getID_PatientJourneyTarget());
			targetVo.setTargetDate(targets.get(k).getTargetDate());
			targetVo.setWeekNumber(targets.get(k).getWeekNumber());
			targetVo.setPathwayTarget(targets.get(k).getPathwayTarget());
			
			targetVo.setCurrentStatus(targets.get(k).getCurrentStatus());

			if (patientJourneyTargetRefVo != null && patientJourneyTargetRefVo.getID_PatientJourneyTarget().equals(targetVo.getID_PatientJourneyTarget()))
				targetVo.setDisplayTicked(Boolean.TRUE);

			dispTargets.add(targetVo);
		}
		if (dispTargets.size() == 0)
			return null;

		return dispTargets;				
	}
		
	private void populateTargets(PatientJourneyInterfaceVo selectedPatientPathwayJourney,	PatientJourneyTargetRefVo preSelectedTargetRef)
	{
		if (selectedPatientPathwayJourney == null)
			return;
		
		PatientJourneyTargetForPathwayCommentsVoCollection collTargets = processTargets(selectedPatientPathwayJourney, preSelectedTargetRef);
		populateTargetsGrid(collTargets);
	}
	
	private void populateTargetsGrid(PatientJourneyTargetForPathwayCommentsVoCollection collTargets)
	{
		form.lyrCommentWizard().tabPageDetails().grdTargets().getRows().clear();

		if (collTargets == null)
			return;	

		for (int i=0; i< collTargets.size(); i++)
		{	
			if (collTargets.get(i) == null)
				continue;
			grdTargetsRow targetRow = form.lyrCommentWizard().tabPageDetails().grdTargets().getRows().newRow();
			targetRow.setColTarget(collTargets.get(i).getPathwayTarget().getTarget().getName());
			targetRow.setColSelect(Boolean.TRUE.equals(collTargets.get(i).getDisplayTicked()) ? Boolean.TRUE : Boolean.FALSE);
			
			targetRow.setValue(collTargets.get(i));
		}
		
	}
	private PatientJourneyTargetForPathwayCommentsVoCollection processTargets(PatientJourneyInterfaceVo selectedPatientPathwayJourney,	PatientJourneyTargetRefVo preSelectedTargetRef)
	{
		if (selectedPatientPathwayJourney == null || selectedPatientPathwayJourney.getJourneyTargets() == null || selectedPatientPathwayJourney.getJourneyTargets().size() == 0)
			return null;
		if (form.getLocalContext().getPreSelectedTargetRef() == null && PatientJourneyAction.ADDTARGETCOMMENT.equals(form.getLocalContext().getCommentType()))
			form.getLocalContext().setPreSelectedTargetRef(form.getGlobalContext().Pathways.getSelectedPatientJourneyTargetRef());
		PatientJourneyJourneyTargetInterfaceVoCollection targets = (PatientJourneyJourneyTargetInterfaceVoCollection) selectedPatientPathwayJourney.getJourneyTargets().clone();
		PatientJourneyTargetForPathwayCommentsVoCollection displayTargets = formatTargetsForDisplay(targets, form.getLocalContext().getPreSelectedTargetRef());
		
		return displayTargets;
	}

	@Override
	protected void onBtnSaveClick() throws PresentationLogicException
	{
		if (save())
		{	
			if (NEW_COMMENT_MODE.equals(form.getLocalContext().getDialogFunctionMode()) || VALIDATE_MODE.equals(form.getLocalContext().getDialogFunctionMode()))
				engine.close(DialogResult.OK);
		}
	}
	private boolean save()
	{
		PatientJourneyCommentVo recordToSave = populateDataFromScreen(form.getLocalContext().getCurrentPathwayJourney(), form.getLocalContext().getCurrentComment());
		PathwayLiteVo pathway = domain.getPathway(form.getGlobalContext().Pathways.getSelectedPathway());
		
		String[] errors = recordToSave.validate(validateUI());
		
		if (errors != null)
		{
			form.lyrCommentWizard().showtabPageDetails();
			engine.showErrors("Comment Validation Errors", errors);
			return false;
		}
		try 
		{
			Date prevValidationDate = form.getLocalContext().getCurrentPathwayJourneyIsNotNull() ? form.getLocalContext().getCurrentPathwayJourney().getNextValidationDate() : null;
			domain.save(form.getLocalContext().getCurrentPathwayJourney(),pathway, form.lyrCommentWizard().tabPageDetails().dteNextValidation().getValue(), recordToSave, VALIDATE_MODE.equals(form.getLocalContext().getDialogFunctionMode()), prevValidationDate);
		}
		catch (StaleObjectException ex)
		{
			engine.showMessage(ConfigFlag.UI.STALE_OBJECT_MESSAGE.getValue());
			if (NEW_COMMENT_MODE.equals(form.getLocalContext().getDialogFunctionMode()) || VALIDATE_MODE.equals(form.getLocalContext().getDialogFunctionMode()))
				engine.close(DialogResult.ABORT);
			return false;
		}
		catch (DomainInterfaceException e)
		{
			engine.showMessage(e.getMessage());
			return false;
		}
		return true;
	}	
			
	@Override
	protected void onGrdTargetsGridCheckBoxClicked(int column, grdTargetsRow row, boolean isChecked) throws PresentationLogicException
	{
		form.getLocalContext().setPreSelectedTargetRef(isChecked ? row.getValue() : null);
		form.getLocalContext().setPreSelectedEventRef(null);
				
		grdTargetsRowCollection targetRows = form.lyrCommentWizard().tabPageDetails().grdTargets().getRows();
		
		for (int i=0; targetRows != null && targetRows.size() > 0 && i <targetRows.size() ; i++)
		{
			if (targetRows.get(i) == null || targetRows.get(i).getValue() == null || row.getValue().getID_PatientJourneyTarget().equals(targetRows.get(i).getValue().getID_PatientJourneyTarget()))
				continue;
			targetRows.get(i).setColSelect(Boolean.FALSE);
		}		
		
	}
	@Override
	protected void onGrdEventsGridCheckBoxClicked(int column, grdEventsRow row, boolean isChecked) throws PresentationLogicException
	{
		form.getLocalContext().setPreSelectedEventRef(isChecked ? row.getValue() : null);
		form.getLocalContext().setPreSelectedTargetRef(null);
		grdEventsRowCollection eventRows = form.lyrCommentWizard().tabPageDetails().grdEvents().getRows();
		
		for (int i=0; eventRows != null && eventRows.size() > 0 && i <eventRows.size() ; i++)
		{
			if (eventRows.get(i) == null || eventRows.get(i).getValue() == null || row.getValue().getID_PatientEvent().equals(eventRows.get(i).getValue().getID_PatientEvent()))
					continue;
			eventRows.get(i).setColSelect(Boolean.FALSE);
		}			
	}

	@Override
	protected void onRadioButtonGroupCommentTypesValueChanged() throws PresentationLogicException
	{
		form.getLocalContext().setPreSelectedEventRef(null);
		form.getLocalContext().setPreSelectedTargetRef(null);
		
		populateEvents(form.getLocalContext().getCurrentPathwayJourney(), null);
		populateTargets(form.getLocalContext().getCurrentPathwayJourney(), null);
		
		getCommentType();		
		updateControlsState();
	}

	private int getCommentType()
	{
		GroupCommentTypesEnumeration commentType = form.lyrCommentWizard().tabPageDetails().GroupCommentTypes().getValue();
		
		if (GroupCommentTypesEnumeration.rdoPathway.equals(commentType))
		{
			form.getLocalContext().setCommentType(PatientJourneyAction.ADDPATHWAYCOMMENT);
		}
		else if (GroupCommentTypesEnumeration.rdoEvent.equals(commentType))
		{
			form.getLocalContext().setCommentType(PatientJourneyAction.ADDEVENTCOMMENT);
		}
		else if (GroupCommentTypesEnumeration.rdoTarget.equals(commentType))
		{
			form.getLocalContext().setCommentType(PatientJourneyAction.ADDEVENTTOTARGET);
		}
		
		return 0;
	}
		
	private void setCommentType(PatientJourneyCommentVo currentComment, PatientJourneyAction patientJourneyAction, boolean isNewCommentMode, Boolean isViewCommentMode, Boolean isValidateMode)
	{
		CommentLevel currentCommentLevel = currentComment != null && currentComment.getCommentLevelIsNotNull() ? currentComment.getCommentLevel() : null;
		
		if (PatientJourneyAction.ADDPATHWAYCOMMENT.equals(patientJourneyAction) || isValidateMode || (isViewCommentMode  &&  CommentLevel.PATHWAY.equals(currentCommentLevel)))
		{
			form.lyrCommentWizard().tabPageDetails().GroupCommentTypes().setValue(GroupCommentTypesEnumeration.rdoPathway);
		}
		else if (PatientJourneyAction.ADDEVENTCOMMENT.equals(patientJourneyAction) || (isViewCommentMode  && CommentLevel.EVENT.equals(currentCommentLevel)))
		{
			form.lyrCommentWizard().tabPageDetails().GroupCommentTypes().setValue(GroupCommentTypesEnumeration.rdoEvent);
			form.getLocalContext().setPreSelectedEventRef(currentComment != null && currentComment.getLinkedEventIsNotNull() ? currentComment.getLinkedEvent() : form.getLocalContext().getPreSelectedEventRef());
			populateEvents(form.getLocalContext().getCurrentPathwayJourney(), form.getLocalContext().getPreSelectedEventRef());
		}
		else if (PatientJourneyAction.ADDTARGETCOMMENT.equals(patientJourneyAction) ||(isViewCommentMode && CommentLevel.TARGET.equals(currentCommentLevel)))
		{
			form.lyrCommentWizard().tabPageDetails().GroupCommentTypes().setValue(GroupCommentTypesEnumeration.rdoTarget);
			form.getLocalContext().setPreSelectedTargetRef(currentComment != null && currentComment.getLinkedTargetIsNotNull() ? currentComment.getLinkedTarget() : form.getGlobalContext().Pathways.getSelectedPatientJourneyTargetRef());
			populateTargets(form.getLocalContext().getCurrentPathwayJourney(), form.getLocalContext().getPreSelectedTargetRef());
		}
		getCommentType();
		updateControlsState();
	}

	@Override
	protected void onBtnCloseClick() throws PresentationLogicException
	{
		engine.close(DialogResult.CANCEL);		
	}

	@Override
	protected void onDteNextValidationValueChanged() throws PresentationLogicException
	{
		form.lyrCommentWizard().tabPageDetails().txtReason().setValue(null);
		form.lyrCommentWizard().tabPageDetails().cmbReason().setValue(null);
		updateControlsState();
	}

	@Override
	protected void onBtnRIEClick() throws PresentationLogicException
	{
		markAsRIE();
	}
	
	private void markAsRIE() 
	{
		engine.open(form.getForms().Core.RieConfirmationDialog);
	}

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

	@Override
	protected void onFormDialogClosed(FormName formName, DialogResult result) throws PresentationLogicException
	{
		if(formName.equals(form.getForms().Core.RieConfirmationDialog) && DialogResult.OK.equals(result))
		{
			doRIE();
		}	
		
		if (formName.equals(form.getForms().Pathways.PathwayNoteCorrectionDialog) && DialogResult.OK.equals(result))
		{
			open();
		}
	}
	
	private void doRIE() 
	{
		boolean isStale = false;
		if(domain.isStale(form.getLocalContext().getCurrentComment()))
		{
			isStale = true;
		}
		
		if(isStale)
		{
			engine.showMessage(ConfigFlag.UI.STALE_OBJECT_MESSAGE.getValue());
			return;
		}
		
		try 
		{
			domain.markAsRie(form.getLocalContext().getCurrentComment(), engine.getFormName(), form.getGlobalContext().Core.getPatientShort().getID_Patient(), null, null, form.getGlobalContext().Core.getRieMessage());
		} 
		catch (StaleObjectException e) 
		{
			e.printStackTrace();
			engine.showMessage(ims.configuration.gen.ConfigFlag.UI.STALE_OBJECT_MESSAGE.getValue());
			form.getLocalContext().setCurrentComment(domain.getCommentDetails(form.getGlobalContext().Pathways.getPatientJourneySelectedComment()));
			
			populateScreenFromData(form.getLocalContext().getCurrentComment(),false, true, false);
			return;
		}
		
		engine.close(DialogResult.CANCEL);
	}
}
