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

package ims.pathways.forms.pathwayconfiguration;

import ims.configuration.gen.ConfigFlag;
import ims.core.vo.enums.MosType;
import ims.core.vo.lookups.LookupHelper;
import ims.core.vo.lookups.PreActiveActiveInactiveStatus;
import ims.core.vo.lookups.PreActiveActiveInactiveStatusCollection;
import ims.domain.exceptions.DomainInterfaceException;
import ims.domain.exceptions.StaleObjectException;
import ims.domain.exceptions.UnqViolationUncheckedException;
import ims.framework.Control;
import ims.framework.FormName;
import ims.framework.MessageButtons;
import ims.framework.MessageIcon;
import ims.framework.enumerations.DialogResult;
import ims.framework.enumerations.FormMode;
import ims.framework.exceptions.CodingRuntimeException;
import ims.framework.exceptions.PresentationLogicException;
import ims.framework.utils.Color;
import ims.pathways.configuration.vo.PathwayRefVo;
import ims.pathways.configuration.vo.TargetRefVoCollection;
import ims.pathways.forms.pathwayconfiguration.GenForm.ctnTargetsContainer.grdTargetsRow;
import ims.pathways.vo.PathwayShortVoCollection;
import ims.pathways.vo.PathwayTargetExternalEventMappingVo;
import ims.pathways.vo.PathwayTargetExternalEventMappingVoCollection;
import ims.pathways.vo.PathwayTargetRTTEventVo;
import ims.pathways.vo.PathwayTargetRTTEventVoCollection;
import ims.pathways.vo.PathwayTargetVo;
import ims.pathways.vo.PathwayTargetVoCollection;
import ims.pathways.vo.PathwayVo;
import ims.pathways.vo.TargetShortVo;
import ims.pathways.vo.lookups.JourneyCountType;

import java.util.ArrayList;

public class Logic extends BaseLogic
{
	private static final long	serialVersionUID		= 1L;
	private static final String	WARNING_ACTIVE_PATHWAY	= "All Pathway Targets should be Active or Inactive when activating the Pathway";

	protected void onFormOpen(Object[] args) throws ims.framework.exceptions.PresentationLogicException
	{
		// Mode of form is passed in from Pathways.PathwaySearchAndSelect
		// Global Contexts also set in Pathways.PathwaySearchAndSelect
		FormMode mode = FormMode.VIEW;
		if (args != null && args.length == 1)
		{
			if (args[0] instanceof FormMode)
				mode = (FormMode) args[0];
		}

		initialize(mode);
	}

	private void initialize(FormMode mode)
	{
		form.customControlMappings().initialize();

		PathwayRefVo voPathwayToCopy = form.getGlobalContext().Pathways.getPathwayToCopy();
		PathwayRefVo voPathwayToEdit = form.getGlobalContext().Pathways.getSelectedPathway();
		PathwayVo voPathway = null;
		//form.customControlConsultant().setHcpSearchType(HCPSearchType.MEDIC);
		
		//WDEV-5193 
		form.customControlMos().initialize(MosType.MEDIC);

		if (mode.equals(FormMode.EDIT))
		{
			if (voPathwayToCopy != null)
			{
				voPathway = copyPathway(voPathwayToCopy);
				populateScreenFromData(voPathway);
				form.setMode(FormMode.EDIT);
			}
			else if (voPathwayToEdit != null)
			{
				if (voPathwayToEdit.getID_Pathway() == null)
				{
					newInstance();
				}
				else
				{
					setPathwayToDisplay(voPathwayToEdit);
					form.setMode(FormMode.EDIT);
					form.chkNonStandard().setEnabled(!alreadyWithinSpeciality());
					form.chkNonStandard().setEnabled(true);
				}
			}
		}
		else if (mode.equals(FormMode.VIEW))
		{
			if (voPathwayToEdit != null)
			{
				setPathwayToDisplay(voPathwayToEdit);
				form.setMode(FormMode.VIEW);
			}
		}
		
		updateJourneyLabels();
	}

	private void setPathwayToDisplay(PathwayRefVo voPathwayToEdit)
	{
		PathwayVo voPathway = domain.getPathway(voPathwayToEdit);
		form.getLocalContext().setSelectedPathway(voPathway);
		form.getLocalContext().setSelectedPathwayTargets(domain.listPathwayTargetsByPathway(voPathwayToEdit));
		if(form.getLocalContext().getSelectedPathwayTargetsIsNotNull())
		{
			form.getGlobalContext().Pathways.setSelectedPathwayTargetsExternalMappings(domain.listPathwayTargetsExMappingsByPathwayTargets(form.getLocalContext().getSelectedPathwayTargets().toRefVoCollection()));
			form.getGlobalContext().Pathways.setSelectedPathwayTargetsRTTEvents(domain.listPathwayTargetsRTTEventsByPathwayTargets(form.getLocalContext().getSelectedPathwayTargets().toRefVoCollection()));
		}
		populateScreenFromData(voPathway);
	}

	/**
	 * clear out id's of record we are copying and set all status's to preactive
	 * note : does not copy inactive child records as required
	 * @param voPathwayToCopy
	 * @return
	 */
	private PathwayVo copyPathway(PathwayRefVo voPathwayToCopy)
	{
		PathwayVo voPathway = domain.getPathway(voPathwayToCopy);
		form.getLocalContext().setSelectedPathwayTargets(domain.listPathwayTargetsByPathway(voPathwayToCopy));
		
		if(form.getLocalContext().getSelectedPathwayTargetsIsNotNull())
		{
			form.getGlobalContext().Pathways.setSelectedPathwayTargetsExternalMappings(domain.listPathwayTargetsExMappingsByPathwayTargets(form.getLocalContext().getSelectedPathwayTargets().toRefVoCollection()));
			form.getGlobalContext().Pathways.setSelectedPathwayTargetsRTTEvents(domain.listPathwayTargetsRTTEventsByPathwayTargets(form.getLocalContext().getSelectedPathwayTargets().toRefVoCollection()));
		}
		
		// clearing out existing id for a copy
		voPathway.setID_Pathway(null);
		voPathway.setStatus(PreActiveActiveInactiveStatus.PREACTIVE);

		form.getLocalContext().setSelectedPathwayTargets(domain.listPathwayTargetsByPathway(voPathwayToCopy));
		form.getLocalContext().setSelectedPathway(voPathway);

		// clearing out existing id's for a copy
		if (form.getLocalContext().getSelectedPathwayTargetsIsNotNull())
		{
			PathwayTargetVoCollection removedCollection = new PathwayTargetVoCollection();
			for (int i = 0; i < form.getLocalContext().getSelectedPathwayTargets().size(); i++)
			{
				// dont copy inactive pathway targets
				if (form.getLocalContext().getSelectedPathwayTargets().get(i).getStatus().equals(PreActiveActiveInactiveStatus.INACTIVE))
				{
					removedCollection.add(form.getLocalContext().getSelectedPathwayTargets().get(i));
					continue;
				}

				form.getLocalContext().getSelectedPathwayTargets().get(i).setID_PathwayTarget(null);
				form.getLocalContext().getSelectedPathwayTargets().get(i).setStatus(PreActiveActiveInactiveStatus.PREACTIVE);
			}

			for (int i = 0; i < removedCollection.size(); i++)
				form.getLocalContext().getSelectedPathwayTargets().remove(removedCollection.get(i));
		}
		
		if(form.getGlobalContext().Pathways.getSelectedPathwayTargetsExternalMappingsIsNotNull())
		{
			for(int i=0;i<form.getGlobalContext().Pathways.getSelectedPathwayTargetsExternalMappings().size(); i++)
			{
				form.getGlobalContext().Pathways.getSelectedPathwayTargetsExternalMappings().get(i).setID_PathwayTargetExternalEventMapping(null);
				form.getGlobalContext().Pathways.getSelectedPathwayTargetsExternalMappings().get(i).getPathwayTarget().setID_PathwayTarget(null);
			}
		}
		
		if(form.getGlobalContext().Pathways.getSelectedPathwayTargetsRTTEventsIsNotNull())
		{
			for(int i=0;i<form.getGlobalContext().Pathways.getSelectedPathwayTargetsRTTEvents().size(); i++)
			{
				form.getGlobalContext().Pathways.getSelectedPathwayTargetsRTTEvents().get(i).setID_PathwayTargetRTTEvent(null);
				form.getGlobalContext().Pathways.getSelectedPathwayTargetsRTTEvents().get(i).getPathwayTarget().setID_PathwayTarget(null);
			}
		}
		
		return voPathway;
	}

	protected void onBtnNewClick() throws ims.framework.exceptions.PresentationLogicException
	{
		newInstance();
	}

	private void newInstance()
	{
		form.getLocalContext().setSelectedPathway(null);
		form.getLocalContext().setSelectedPathwayTargets(null);

		form.getGlobalContext().Pathways.setSelectedTarget(null);
		form.getGlobalContext().Pathways.setSelectedPathwayTargetExternalMappings(null);
		form.getGlobalContext().Pathways.setSelectedPathwayTargetRTTEvents(null);

		form.getGlobalContext().Pathways.setSelectedPathwayTargetsExternalMappings(null);
		form.getGlobalContext().Pathways.setSelectedPathwayTargetsRTTEvents(null);
		
		form.getGlobalContext().Pathways.setPathwayToCopy(null);
		form.getGlobalContext().Pathways.setSelectedPathwaySpecialty(null);
		form.getGlobalContext().Pathways.setSelectedPathwayStatus(PreActiveActiveInactiveStatus.PREACTIVE);
		form.getGlobalContext().Pathways.setSelectedTargets(null);

		clearScreen();
		form.setMode(FormMode.EDIT);
		
		if (ConfigFlag.DOM.RTT_STANDARD_PATHWAY.getValue())
		{
			form.cmbJourneyCountType().setValue(JourneyCountType.DAYS);
			form.intNumWeeks().setValue(127);
		}
		//WDEV-17706
		else
			form.cmbJourneyCountType().setValue(JourneyCountType.WEEKS);
		
		bindcmbStatusLookup();
		showSelectableStatuses(null);
		form.cmbStatus().setValue(PreActiveActiveInactiveStatus.PREACTIVE);
		form.chkNonStandard().setEnabled(!alreadyWithinSpeciality());
	}

	protected void onBtnEditClick() throws ims.framework.exceptions.PresentationLogicException
	{
		bindcmbStatusLookup();
		showSelectableStatuses(form.getLocalContext().getSelectedPathway());
		form.setMode(FormMode.EDIT);
		form.chkNonStandard().setEnabled(!alreadyWithinSpeciality());
	}

	protected void onBtnSaveClick() throws ims.framework.exceptions.PresentationLogicException
	{
		if (save())
			open();
	}

	private void open()
	{
		clearScreen();
		if (form.getLocalContext().getSelectedPathwayIsNotNull() && form.getLocalContext().getSelectedPathway().getID_PathwayIsNotNull())
		{
			form.getLocalContext().setSelectedPathwayTargets(domain.listPathwayTargetsByPathway(form.getLocalContext().getSelectedPathway()));
			form.getLocalContext().setSelectedPathway(domain.getPathway(form.getLocalContext().getSelectedPathway()));
			if(form.getLocalContext().getSelectedPathwayTargetsIsNotNull())
			{
				form.getGlobalContext().Pathways.setSelectedPathwayTargetsExternalMappings(domain.listPathwayTargetsExMappingsByPathwayTargets(form.getLocalContext().getSelectedPathwayTargets().toRefVoCollection()));
				form.getGlobalContext().Pathways.setSelectedPathwayTargetsRTTEvents(domain.listPathwayTargetsRTTEventsByPathwayTargets(form.getLocalContext().getSelectedPathwayTargets().toRefVoCollection()));	
			}
			populateScreenFromData(form.getLocalContext().getSelectedPathway());			
		}
		updateJourneyLabels();

		form.setMode(FormMode.VIEW);
	}

	private boolean save()
	{
		if(!checkChildsStatus())
			return false;
		
		PathwayVo voPathway = form.getLocalContext().getSelectedPathway();
		voPathway = populateDataFromScreen(voPathway);

		// Pathway
		//WDEV-17706
		String[] uiErrors = getUIValidationRules(voPathway);
		
		if (uiErrors != null && uiErrors.length >0)
		{
			engine.showErrors(uiErrors);
			return false;
		}
		
		String[] errors = voPathway.validate();

		if (errors != null && errors.length >0)
		{
			engine.showErrors(errors);
			return false;
		}

		// PathwayTargets
		PathwayTargetVoCollection voCollPathwayTargets = form.getLocalContext().getSelectedPathwayTargets();
		if (voCollPathwayTargets != null && voCollPathwayTargets.size() > 0)
		{
			String[] arrErrors2 = voCollPathwayTargets.validate(getPathwayTargetUIErrors());
			if (arrErrors2 != null)
			{
				engine.showErrors(arrErrors2);
				return false;
			}
		}
		else
		{
			if (voPathway.getStatus().equals(PreActiveActiveInactiveStatus.ACTIVE))
			{
				engine.showErrors(new String[]{"At least one Pathway Target is mandatory when saving an active Pathway"});
				return false;
			}
		}

		// WDEV-3746
		if (!validateStatus(voPathway, voCollPathwayTargets))
		{
			engine.showErrors(new String[]{"Please ensure that all Pathway Targets are Active or Inactive before activating this Pathway"});
			return false;
		}

		// External Mappings - dont validate here as the status is handled in
		// the impl
		PathwayTargetExternalEventMappingVoCollection voCollExMappings = getSelectedExternalMappings();

		// RTT Mappings - dont validate here as the status is handled in the
		// impl
		PathwayTargetRTTEventVoCollection voCollRttMappings = getSelectedRTTEevents();

		try
		{
			voPathway = domain.savePathway(voPathway, voCollPathwayTargets, voCollExMappings, voCollRttMappings);
		}
		catch (StaleObjectException e)
		{
			engine.showMessage(ConfigFlag.UI.STALE_OBJECT_MESSAGE.getValue());
			open();
			return false;
		}
		catch (DomainInterfaceException e)
		{
			engine.showMessage(e.getMessage());
			return false;
		}
		catch(UnqViolationUncheckedException e)
		{
			engine.showErrors("Taxonomy Map error", new String[]{"TaxonomyMap must be unique!"});
			return false;
		}
		form.getLocalContext().setSelectedPathway(voPathway);
		return true;
	}
	//WDEV-17706
	private String[] getUIValidationRules(PathwayVo voPathway)
	{
		ArrayList<String> errors = new ArrayList<String>();

		if (voPathway.getName() == null)
		{
			errors.add("Name is mandatory.");
		}

		if (voPathway.getSpecialty() == null)
		{
			errors.add("Specialty is mandatory.");
		}

		if (voPathway.getJourneyCountType() == null)
		{
			errors.add("Journey Count is mandatory.");
		}

		if (voPathway.getStatus() == null)
		{
			errors.add("Status is mandatory.");
		}

		if (voPathway.getNumWeeks() == null)
		{		
			if (JourneyCountType.DAYS.equals(form.cmbJourneyCountType().getValue()))
			{
				errors.add("Referral to treatment in: # days is mandatory.");
			}
			if (JourneyCountType.WEEKS.equals(form.cmbJourneyCountType().getValue()))
			{
				errors.add("Referral to treatment in: # weeks is mandatory.");
			}
		}	

		if (errors != null && errors.size() >0)
		{
			return errors.toArray(new String[errors.size()]);

		}
		return null;
	}

	private boolean validateStatus(PathwayVo voPathway, PathwayTargetVoCollection voCollPathwayTargets)
	{
		if (!voPathway.getStatus().equals(PreActiveActiveInactiveStatus.ACTIVE))
			return true;

		int preactivecount = 0;
		for (int i = 0; i < voCollPathwayTargets.size(); i++)
		{
			PathwayTargetVo voPathwayTarget = voCollPathwayTargets.get(i);
			if (voPathwayTarget.getStatus().equals(PreActiveActiveInactiveStatus.PREACTIVE))
				preactivecount++;
		}

		return preactivecount == 0;
	}

	/**
	 * go through the pathwaytargets grid and get the collection of mappings
	 * from each one ensuring to set the pathway target reference
	 * 
	 * @return
	 */
	private PathwayTargetExternalEventMappingVoCollection getSelectedExternalMappings()
	{
		PathwayTargetExternalEventMappingVoCollection collMappings = new PathwayTargetExternalEventMappingVoCollection();
		for (int i = 0; i < form.ctnTargets().grdTargets().getRows().size(); i++)
		{
			grdTargetsRow row = form.ctnTargets().grdTargets().getRows().get(i);
			PathwayTargetExternalEventMappingVoCollection ptMappings = row.getColExtMappings();
			if (ptMappings != null)
			{
				for (int p = 0; p < ptMappings.size(); p++)
				{
					PathwayTargetExternalEventMappingVo mapping = ptMappings.get(p);
					mapping.setPathwayTarget(row.getValue());
					collMappings.add(mapping);
				}
			}
		}

		return collMappings;
	}

	/**
	 * go through the pathwaytargets grid and get the collection of mappings
	 * from each one ensuring to set the pathway target reference
	 * 
	 * @return
	 */
	private PathwayTargetRTTEventVoCollection getSelectedRTTEevents()
	{
		PathwayTargetRTTEventVoCollection collMappings = new PathwayTargetRTTEventVoCollection();
		for (int i = 0; i < form.ctnTargets().grdTargets().getRows().size(); i++)
		{
			grdTargetsRow row = form.ctnTargets().grdTargets().getRows().get(i);
			PathwayTargetRTTEventVoCollection ptMappings = row.getColRTTMappings();
			if (ptMappings != null)
			{
				for (int p = 0; p < ptMappings.size(); p++)
				{
					PathwayTargetRTTEventVo mapping = ptMappings.get(p);
					mapping.setPathwayTarget(row.getValue());
					collMappings.add(mapping);
				}
			}
		}

		return collMappings;
	}

	private String[] getPathwayTargetUIErrors()
	{
		//WDEV-20014
		if (ConfigFlag.DOM.RTT_STANDARD_PATHWAY.getValue())
			return null;
		
		// check all the pathway target week numbers and make sure they are
		// within the range (0 - <pathway num weeks>)
		Integer pathwayNumWeeks = form.intNumWeeks().getValue();
		for (int i = 0; i < form.ctnTargets().grdTargets().getRows().size(); i++)
		{
			grdTargetsRow row = form.ctnTargets().grdTargets().getRows().get(i);
			Integer pathwayTargetWeekNo = row.getColWeekNo();
			if (pathwayTargetWeekNo != null && pathwayNumWeeks != null)
			{
				if (pathwayTargetWeekNo > pathwayNumWeeks)
					return new String[]{"Pathway Target Week No.'s must be within the range 0 to 'Referral to Treatment in' weeks"};
			}
		}

		return null;
	}

	protected void onBtnCancelClick() throws ims.framework.exceptions.PresentationLogicException
	{
		open();
	}

	protected void onFormDialogClosed(FormName formName, DialogResult result) throws PresentationLogicException
	{
		if (formName.equals(form.getForms().Pathways.PathwayTargetConfigDialog))
		{
			if (result.equals(DialogResult.OK))
			{
				addPathwayTargetToGrid();
			}
			updateControlState(); //WDEV-18747
		}
	}

	private void addPathwayTargetToGrid()
	{
		PathwayTargetExternalEventMappingVoCollection voCollEventMappings = form.getGlobalContext().Pathways.getSelectedPathwayTargetExternalMappings();
		PathwayTargetRTTEventVoCollection voCollRTTMappings = form.getGlobalContext().Pathways.getSelectedPathwayTargetRTTEvents();
		TargetShortVo voTarget = form.getGlobalContext().Pathways.getSelectedTarget();

		if (voTarget == null)
			throw new CodingRuntimeException("Selected target not set in dialog");

		addSelectedMappingsToGlobalContext(voCollEventMappings, voCollRTTMappings);

		boolean bTargetFound = false;
		for (int i = 0; i < form.ctnTargets().grdTargets().getRows().size(); i++)
		{
			PathwayTargetVo voPathwayTarget = form.ctnTargets().grdTargets().getRows().get(i).getValue();
			if (voPathwayTarget != null)
			{
				if (voPathwayTarget.getTargetIsNotNull())
				{
					if (voPathwayTarget.getTarget().equals(voTarget))
					{
						bTargetFound = true;
						updatePathwayTargetRow(voPathwayTarget, voCollEventMappings, voCollRTTMappings);
						break;
					}
				}
			}
		}
		if (!bTargetFound)
		{
			addPathwayTargetRow(voTarget, voCollEventMappings, voCollRTTMappings);
		}
	}

	private void addPathwayTargetRow(TargetShortVo voTarget, PathwayTargetExternalEventMappingVoCollection voCollEventMappings, PathwayTargetRTTEventVoCollection voCollRTTMappings)
	{
		PathwayTargetVo voPathwayTarget = new PathwayTargetVo();
		voPathwayTarget.setTarget(voTarget);

		GenForm.ctnTargetsContainer.grdTargetsRow row = form.ctnTargets().grdTargets().getRows().newRow();

		// storing the mapping for the pathway target
		row.setColExtMappings(voCollEventMappings);
		row.setColRTTMappings(voCollRTTMappings);

		row.setColWeekNo(voPathwayTarget.getTargetPeriod());
		row.setColTarget(voPathwayTarget.getTarget());
		if (voPathwayTarget.getTargetIsNotNull())
			row.setColTargetDesc(voPathwayTarget.getTarget().getDescription());
		if (voPathwayTarget.getActivateTargetIsNotNull())
			row.setColActivateTarget(voPathwayTarget.getActivateTarget());

		// cant add inactive records
		PreActiveActiveInactiveStatusCollection excludedColl = new PreActiveActiveInactiveStatusCollection();
		excludedColl.add(PreActiveActiveInactiveStatus.INACTIVE);

		// cant add preactive children
		if (form.cmbStatus().getValue() != null && form.cmbStatus().getValue().equals(PreActiveActiveInactiveStatus.ACTIVE))
			excludedColl.add(PreActiveActiveInactiveStatus.PREACTIVE);

		loadStatusComboInGridRow(row, excludedColl);
		// default new records to active
		row.getColStatus().setValue(PreActiveActiveInactiveStatus.PREACTIVE);

		row.setValue(voPathwayTarget);

		if (form.getGlobalContext().Pathways.getSelectedTargets() == null)
			form.getGlobalContext().Pathways.setSelectedTargets(new TargetRefVoCollection());

		form.getGlobalContext().Pathways.getSelectedTargets().add(voTarget);

		form.ctnTargets().grdTargets().setValue(null);

	}

	private void loadStatusComboInGridRow(grdTargetsRow row, PreActiveActiveInactiveStatusCollection excludedColl)
	{
		PreActiveActiveInactiveStatusCollection collLookups = LookupHelper.getPreActiveActiveInactiveStatus(domain.getLookupService());
		for (int i = 0; i < collLookups.size(); i++)
		{
			if (excludedColl != null)
			{
				if (!excludedColl.contains(collLookups.get(i)))
					row.getColStatus().newRow(collLookups.get(i), collLookups.get(i).getText());
			}
			else
				row.getColStatus().newRow(collLookups.get(i), collLookups.get(i).getText());
		}
	}

	private void updatePathwayTargetRow(PathwayTargetVo voPathwayTarget, PathwayTargetExternalEventMappingVoCollection voCollEventMappings, PathwayTargetRTTEventVoCollection voCollRTTMappings)
	{
		GenForm.ctnTargetsContainer.grdTargetsRow row = form.ctnTargets().grdTargets().getSelectedRow();

		// storing the mapping for the pathway target
		row.setColExtMappings(voCollEventMappings);
		row.setColRTTMappings(voCollRTTMappings);

		row.setColWeekNo(voPathwayTarget.getTargetPeriod());
		row.setColTarget(voPathwayTarget.getTarget());
		if (voPathwayTarget.getTargetIsNotNull())
			row.setColTargetDesc(voPathwayTarget.getTarget().getDescription());

		if (voPathwayTarget.getActivateTargetIsNotNull())
			row.setColActivateTarget(voPathwayTarget.getActivateTarget());

		row.setValue(voPathwayTarget);
	}

	protected void onFormModeChanged()
	{
		updateControlState();
	}

	private void updateControlState()
	{
		FormMode mode = form.getMode();

		PreActiveActiveInactiveStatus status = null;
		if(form.getLocalContext().getSelectedPathwayIsNotNull())
			status = form.getLocalContext().getSelectedPathway().getStatus();
		
		boolean inactiveStatusSelected = false;
		
		if (status != null)
			inactiveStatusSelected = status.equals(PreActiveActiveInactiveStatus.INACTIVE);

		boolean editingActiveRecord = false;
		if (status != null)
			editingActiveRecord = status.equals(PreActiveActiveInactiveStatus.ACTIVE) && form.getLocalContext().getSelectedPathwayIsNotNull() && form.getLocalContext().getSelectedPathway().getID_PathwayIsNotNull();

		boolean inactivePTStatusSelected = false;
		if(form.ctnTargets().grdTargets().getSelectedRow() != null)
			inactivePTStatusSelected =  form.ctnTargets().grdTargets().getSelectedRow().getValue().getStatusIsNotNull() && form.ctnTargets().grdTargets().getSelectedRow().getValue().getStatus().equals(PreActiveActiveInactiveStatus.INACTIVE);
		
		
		form.getContextMenus().Pathways.getPathwayTargetsADDItem().setVisible(mode.equals(FormMode.EDIT) && !inactiveStatusSelected && !editingActiveRecord & !inactivePTStatusSelected);
		form.getContextMenus().Pathways.getPathwayTargetsEDITItem().setVisible(mode.equals(FormMode.EDIT) && form.ctnTargets().grdTargets().getSelectedRow() != null && !inactiveStatusSelected && !editingActiveRecord && !inactivePTStatusSelected);
		form.getContextMenus().Pathways.getPathwayTargetsVIEWItem().setVisible(form.ctnTargets().grdTargets().getSelectedRow() != null);

		if (form.getMode().equals(FormMode.EDIT))
		{
			for (int i = 0; i < form.ctnTargets().grdTargets().getRows().size(); i++)
				form.ctnTargets().grdTargets().getRows().get(i).setReadOnly(inactiveStatusSelected);

			form.customControlMappings().setComponentMode(FormMode.EDIT);
		}
		else
		{
			form.customControlMappings().setComponentMode(FormMode.VIEW);
			form.btnEdit().setVisible(form.getLocalContext().getSelectedPathwayIsNotNull() && form.getLocalContext().getSelectedPathway().getID_PathwayIsNotNull() && !inactiveStatusSelected);
		}

		form.ctnTargets().grdTargets().setReadOnly(!form.getMode().equals(FormMode.EDIT));
		
		//WDEV-20014
		boolean showJourneyCount = !ConfigFlag.DOM.RTT_STANDARD_PATHWAY.getValue();
		
		form.lblJourneyCountType().setVisible(showJourneyCount);
		form.cmbJourneyCountType().setVisible(showJourneyCount);
		form.cmbJourneyCountType().setEnabled(showJourneyCount && form.getMode().equals(FormMode.EDIT));
		
		form.lblReferralToTreatmentIn().setVisible(showJourneyCount);
		form.intNumWeeks().setVisible(showJourneyCount);
		form.intNumWeeks().setEnabled(showJourneyCount && form.getMode().equals(FormMode.EDIT));
		form.lblJourneyCount().setVisible(showJourneyCount);
		
	}

	protected void clearScreen()
	{
		super.clearScreen();
		form.chkNonStandard().setValue(false);
		//form.customControlConsultant().clear();
		form.customControlMos().clear();
		form.customControlMappings().clear();
		form.ctnTargets().grdTargets().getRows().clear();
		cmbStatusChanged();
		cmbSpecialtyChanged();
	}

	protected void populateScreenFromData(PathwayVo voPathway)
	{
		showSelectableStatuses(voPathway);

		form.getGlobalContext().Pathways.setSelectedTargets(new TargetRefVoCollection());

		super.populateScreenFromData(voPathway);
		if(voPathway.getIsNon18WeekIsNotNull())
			form.chkNonStandard().setValue(voPathway.getIsNon18Week());

		cmbStatusChanged();
		cmbSpecialtyChanged();

		form.customControlMappings().setValue(voPathway.getTaxonomyMaps());
		//form.customControlConsultant().setValue(voPathway.getConsultant());
		form.customControlMos().setValue(voPathway.getConsultant());

		PathwayTargetVoCollection voCollPathwayTargets = form.getLocalContext().getSelectedPathwayTargets();
		form.ctnTargets().grdTargets().getRows().clear();
		if (voCollPathwayTargets != null)
		{
			voCollPathwayTargets.sort();
			for (int i = 0; i < voCollPathwayTargets.size(); i++)
			{
				PathwayTargetVo pt = voCollPathwayTargets.get(i);
				GenForm.ctnTargetsContainer.grdTargetsRow row = form.ctnTargets().grdTargets().getRows().newRow();

				row.setColExtMappings(populateSelectedExternalMappingsFromData(pt));
				row.setColRTTMappings(populateSelectedRTTMappingsFromData(pt));

				row.setColWeekNo(pt.getTargetPeriod());
				if (pt.getTargetIsNotNull())
				{
					form.getGlobalContext().Pathways.getSelectedTargets().add(pt.getTarget());
					row.setColTarget(pt.getTarget());
					row.setColTargetDesc(pt.getTarget().getDescription());
				}
				if (pt.getActivateTargetIsNotNull())
					row.setColActivateTarget(pt.getActivateTarget());
				if (pt.getWarningIndicatorPeriodIsNotNull())
					row.setColWarning(pt.getWarningIndicatorPeriod());
				
				// active cant go to preactive and inactive cant go anywhere
				PreActiveActiveInactiveStatusCollection excludedColl = new PreActiveActiveInactiveStatusCollection();
				if (pt.getStatusIsNotNull())
				{
					if (pt.getStatus().equals(PreActiveActiveInactiveStatus.ACTIVE))
						excludedColl.add(PreActiveActiveInactiveStatus.PREACTIVE);
					else if (pt.getStatus().equals(PreActiveActiveInactiveStatus.INACTIVE))
					{
						excludedColl.add(PreActiveActiveInactiveStatus.PREACTIVE);
						excludedColl.add(PreActiveActiveInactiveStatus.ACTIVE);
					}
				}

				loadStatusComboInGridRow(row, excludedColl);
				row.getColStatus().setValue(pt.getStatus());
				row.setValue(pt);
			}
		}
	}

	private PathwayTargetRTTEventVoCollection populateSelectedRTTMappingsFromData(PathwayTargetVo pt)
	{
		PathwayTargetRTTEventVoCollection mappings = form.getGlobalContext().Pathways.getSelectedPathwayTargetsRTTEvents();
		if (mappings == null)
			return null;

		PathwayTargetRTTEventVoCollection ptMappings = new PathwayTargetRTTEventVoCollection();
		for (int i = 0; i < mappings.size(); i++)
		{
			if (mappings.get(i).getPathwayTarget().getTarget().equals(pt.getTarget()))
				ptMappings.add(mappings.get(i));
		}

		return ptMappings.size() > 0 ? ptMappings : null;
	}

	private PathwayTargetExternalEventMappingVoCollection populateSelectedExternalMappingsFromData(PathwayTargetVo pt)
	{
		PathwayTargetExternalEventMappingVoCollection mappings = form.getGlobalContext().Pathways.getSelectedPathwayTargetsExternalMappings();
		if (mappings == null)
			return null;

		PathwayTargetExternalEventMappingVoCollection ptMappings = new PathwayTargetExternalEventMappingVoCollection();
		for (int i = 0; i < mappings.size(); i++)
		{
			if (mappings.get(i).getPathwayTarget().getTarget().equals(pt.getTarget()))
				ptMappings.add(mappings.get(i));
		}

		return ptMappings.size() > 0 ? ptMappings : null;
	}

	private void addSelectedMappingsToGlobalContext(PathwayTargetExternalEventMappingVoCollection voCollEventMappings, PathwayTargetRTTEventVoCollection voCollRTTMappings)
	{
		PathwayTargetExternalEventMappingVoCollection exMappings = form.getGlobalContext().Pathways.getSelectedPathwayTargetsExternalMappings();
		if (exMappings == null)
			exMappings = new PathwayTargetExternalEventMappingVoCollection();

		PathwayTargetRTTEventVoCollection rttEvents = form.getGlobalContext().Pathways.getSelectedPathwayTargetsRTTEvents();
		if (rttEvents == null)
			rttEvents = new PathwayTargetRTTEventVoCollection();

		if (voCollEventMappings != null)
		{
			for (int i = 0; i < voCollEventMappings.size(); i++)
			{
				exMappings.add(voCollEventMappings.get(i));
			}
		}

		if (voCollRTTMappings != null)
		{
			for (int i = 0; i < voCollRTTMappings.size(); i++)
			{
				rttEvents.add(voCollRTTMappings.get(i));
			}
		}

		form.getGlobalContext().Pathways.setSelectedPathwayTargetsExternalMappings(exMappings);
		form.getGlobalContext().Pathways.setSelectedPathwayTargetsRTTEvents(rttEvents);
	}

	private void showSelectableStatuses(PathwayVo voPathway)
	{
		if (voPathway != null)
		{
			if (voPathway.getID_PathwayIsNotNull())
			{
				if (voPathway.getStatusIsNotNull() && voPathway.getStatus().equals(PreActiveActiveInactiveStatus.ACTIVE))
					form.cmbStatus().removeRow(PreActiveActiveInactiveStatus.PREACTIVE);
				if (voPathway.getStatusIsNotNull() && voPathway.getStatus().equals(PreActiveActiveInactiveStatus.INACTIVE))
				{
					form.cmbStatus().removeRow(PreActiveActiveInactiveStatus.PREACTIVE);
					form.cmbStatus().removeRow(PreActiveActiveInactiveStatus.ACTIVE);
				}
			}
			form.cmbStatus().setValue(voPathway.getStatus());
		}
		else
			form.cmbStatus().removeRow(PreActiveActiveInactiveStatus.INACTIVE);
	}

	protected void onContextMenuItemClick(int menuItemID, Control sender) throws PresentationLogicException
	{
		if (sender.equals(form.ctnTargets().grdTargets()))
		{
			switch (menuItemID)
			{
				case GenForm.ContextMenus.PathwaysNamespace.PathwayTargets.ADD :
					newTarget();
				break;
				case GenForm.ContextMenus.PathwaysNamespace.PathwayTargets.EDIT :
					editTarget();
				break;
				case GenForm.ContextMenus.PathwaysNamespace.PathwayTargets.VIEW :
					viewTarget();
				break;
				default :
				break;
			}
		}
	}

	private void viewTarget()
	{
		engine.open(form.getForms().Pathways.PathwayTargetConfigDialog, new Object[]{FormMode.VIEW});
	}

	private void editTarget()
	{
		engine.open(form.getForms().Pathways.PathwayTargetConfigDialog, new Object[]{FormMode.EDIT});
	}

	private void newTarget()
	{
		form.ctnTargets().grdTargets().setValue(null);
		form.getGlobalContext().Pathways.setSelectedTarget(null);
		form.getGlobalContext().Pathways.setSelectedPathwayTargetExternalMappings(null);
		form.getGlobalContext().Pathways.setSelectedPathwayTargetRTTEvents(null);
		engine.open(form.getForms().Pathways.PathwayTargetConfigDialog, new Object[]{FormMode.EDIT});
	}

	protected void onGrdTargetsSelectionChanged() throws PresentationLogicException
	{
		if (form.ctnTargets().grdTargets().getSelectedRow() != null && form.ctnTargets().grdTargets().getValue() != null)
		{
			form.getGlobalContext().Pathways.setSelectedTarget(form.ctnTargets().grdTargets().getSelectedRow().getColTarget());
			form.getGlobalContext().Pathways.setSelectedPathwayTargetExternalMappings(form.ctnTargets().grdTargets().getSelectedRow().getColExtMappings());
			form.getGlobalContext().Pathways.setSelectedPathwayTargetRTTEvents(form.ctnTargets().grdTargets().getSelectedRow().getColRTTMappings());
		}
		updateControlState();
	}

	protected PathwayVo populateDataFromScreen(PathwayVo value)
	{
		value = super.populateDataFromScreen(value);
		value.setTaxonomyMaps(form.customControlMappings().getValue());
		//value.setConsultant(form.customControlConsultant().getValue());
		value.setConsultant(form.customControlMos().getValue());

		// isDefaultEntry Processing - dont allow setting of isDefault on a not
		// active pathway
		if (form.cmbStatus().getValue() != null)
		{
			if (!form.cmbStatus().getValue().equals(PreActiveActiveInactiveStatus.ACTIVE))
			{
				if (form.chkIsDefault().getValue())
					value.setIsDefault(false);
			}
		}

		value.setIsNon18Week(new Boolean(form.chkNonStandard().getValue()));
				
		form.getLocalContext().setSelectedPathwayTargets(populateInstanceDataFromTargetsGrid(value));
		return value;
	}

	/* UNUSED
	private HcpLiteVo constructHcpLite(MedicLiteVo value)
	{
		if (value == null)
			return null;

		HcpLiteVo voHcp = new HcpLiteVo(value.getID_Hcp(), value.getVersion_Hcp());

		voHcp.setMos(value.getMos());

		return voHcp;
	}*/

	private boolean alreadyWithinSpeciality() 
	{
		if (form.cmbSpecialty().getValue() == null)
			return false;
		
		PathwayVo selectedPathway = form.getLocalContext().getSelectedPathway();
		PathwayShortVoCollection coll = domain.listPathway(form.cmbSpecialty().getValue());
		for(int i=0; i<coll.size(); i++){
			if(coll.get(i).getIsNon18WeekIsNotNull() && coll.get(i).getIsNon18Week())
				if(selectedPathway==null){
					form.getLocalContext().setAlreadyWithinSpeciality(true);
					return true;
				}
				else if(selectedPathway.getID_PathwayIsNotNull() &&
						!selectedPathway.getID_Pathway().equals(coll.get(i).getID_Pathway())){
					form.getLocalContext().setAlreadyWithinSpeciality(true);
					return true;
				}
		}
		
		form.getLocalContext().setAlreadyWithinSpeciality(false);
		return false;
	}

	private PathwayTargetVoCollection populateInstanceDataFromTargetsGrid(PathwayVo value)
	{
		PathwayTargetVoCollection voCollPathwayTargets = new PathwayTargetVoCollection();
		for (int i = 0; i < form.ctnTargets().grdTargets().getRows().size(); i++)
		{
			grdTargetsRow row = form.ctnTargets().grdTargets().getRows().get(i);
			PathwayTargetVo pt = row.getValue();
			if (pt == null)
				pt = new PathwayTargetVo();

			pt.setPathway(value);
			pt.setTargetPeriod(row.getColWeekNo());
			pt.setActivateTarget(row.getColActivateTarget());
			pt.setWarningIndicatorPeriod(row.getColWarning());
			pt.setStatus((PreActiveActiveInactiveStatus) row.getColStatus().getValue());
			pt.setTarget(row.getColTarget());
			voCollPathwayTargets.add(pt);
		}

		return voCollPathwayTargets.size() > 0 ? voCollPathwayTargets : null;
	}

	protected void onLnkPathwayClick() throws PresentationLogicException
	{
		engine.open(form.getForms().Pathways.PathwaySearchAndSelect);
	}

	protected void onCmbStatusValueChanged() throws PresentationLogicException
	{
		cmbStatusChanged();
		checkChildsStatus();
	}

	private boolean checkChildsStatus()
	{
		if (form.cmbStatus().getValue() != null)
		{
			if (form.cmbStatus().getValue().equals(PreActiveActiveInactiveStatus.INACTIVE) && countPreactiveAndActiveRecords() > 0)
			{
				engine.showMessage("If you wish to inactivate the Pathway,All Pathway Targets must be inactivated also.\nSet all Pathway Targets to 'Inactive' now", "Confirmation", MessageButtons.YESNO, MessageIcon.QUESTION);
				return false;
			}
			else if (form.cmbStatus().getValue().equals(PreActiveActiveInactiveStatus.ACTIVE))
			{
				boolean found = false;
				for (int i = 0; i < form.ctnTargets().grdTargets().getRows().size(); i++)
				{
					if (form.ctnTargets().grdTargets().getRows().get(i).getColStatus().getValue() != null
						&& form.ctnTargets().grdTargets().getRows().get(i).getColStatus().getValue().equals(PreActiveActiveInactiveStatus.PREACTIVE))
					{
						found = true;
						form.ctnTargets().grdTargets().getRows().get(i).setBackColor(Color.Red);
						form.ctnTargets().grdTargets().getRows().get(i).setColStatusReadOnly(false);
					}
				}
				if (found)
				{
					engine.showMessage(WARNING_ACTIVE_PATHWAY);
					return false;
				}
			}
			else if (form.cmbStatus().getValue().equals(PreActiveActiveInactiveStatus.PREACTIVE))
			{
				for (int i = 0; i < form.ctnTargets().grdTargets().getRows().size(); i++)
				{
					form.ctnTargets().grdTargets().getRows().get(i).setBackColor(null);
					form.ctnTargets().grdTargets().getRows().get(i).setColStatusReadOnly(false);
				}
			}
		}
		return true;
	}

	private int countPreactiveAndActiveRecords()
	{
		int count = 0;
		for(int i =0;i<form.ctnTargets().grdTargets().getRows().size();i++)
		{
			if(form.ctnTargets().grdTargets().getRows().get(i).getColStatus().getValue() != null && (form.ctnTargets().grdTargets().getRows().get(i).getColStatus().getValue().equals(PreActiveActiveInactiveStatus.PREACTIVE) || form.ctnTargets().grdTargets().getRows().get(i).getColStatus().getValue().equals(PreActiveActiveInactiveStatus.ACTIVE)))
				count ++;
		}
		return count;
	}

	private void cmbStatusChanged()
	{
		form.getGlobalContext().Pathways.setSelectedPathwayStatus(form.cmbStatus().getValue());
		updateControlState();
	}

	protected void onCmbSpecialtyValueChanged() throws PresentationLogicException
	{
		cmbSpecialtyChanged();
	}

	private void cmbSpecialtyChanged()
	{
		form.getGlobalContext().Pathways.setSelectedPathwaySpecialty(form.cmbSpecialty().getValue());
		
		if(form.getMode().equals(FormMode.EDIT))
			if(alreadyWithinSpeciality()){
				form.chkNonStandard().setEnabled(false);
				form.chkNonStandard().setValue(false);
			}
			else
				form.chkNonStandard().setEnabled(!form.chkIsDefault().getValue());
	}

	protected void onGrdTargetsMutableComboBoxSelected(int column, grdTargetsRow row, Object value) throws PresentationLogicException
	{
		if (form.cmbStatus().getValue() != null && form.cmbStatus().getValue().equals(PreActiveActiveInactiveStatus.ACTIVE))
		{
			if (value != null)
			{
				if (value.equals(PreActiveActiveInactiveStatus.ACTIVE) || value.equals(PreActiveActiveInactiveStatus.INACTIVE))
					row.setBackColor(null);
				else if (value.equals(PreActiveActiveInactiveStatus.PREACTIVE))
					checkChildsStatus();
			}
			else
			{
				engine.showMessage("Status is mandatory");
				row.getColStatus().setValue(PreActiveActiveInactiveStatus.ACTIVE);
			}
		}
	}

	protected void onMessageBoxClosed(int messageBoxId, DialogResult result) throws PresentationLogicException
	{
		if(result.equals(DialogResult.YES))
		{
			for(int i=0;i<form.ctnTargets().grdTargets().getRows().size();i++)
			{
				form.ctnTargets().grdTargets().getRows().get(i).getColStatus().setValue(PreActiveActiveInactiveStatus.INACTIVE);
				form.ctnTargets().grdTargets().getRows().get(i).setBackColor(null);
			}
		}
	}

	@Override
	protected void onCmbJourneyCountTypeValueChanged() throws PresentationLogicException 
	{
		updateJourneyLabels();
	}
	//WDEV-19600 -- tool tip style change
	private void updateJourneyLabels() 
	{
		JourneyCountType value = form.cmbJourneyCountType().getValue();
		
		if(value == null)
			value = JourneyCountType.WEEKS;
		
		String textLabel = value.getText(); 
		String txtWeekNoHeaderTooltip = null;
						
		if (textLabel != null)
		{
			form.lblJourneyCount().setValue(textLabel);			
			txtWeekNoHeaderTooltip = textLabel.endsWith("s") ? textLabel.substring(0, textLabel.length() - 1) : textLabel;
			form.ctnTargets().grdTargets().setColWeekNoCaption(txtWeekNoHeaderTooltip + " No.");			
		}		
	}

	@Override
	protected void onChkIsDefaultValueChanged() throws PresentationLogicException {
		if(form.getLocalContext().getAlreadyWithinSpecialityIsNotNull() &&
				!form.getLocalContext().getAlreadyWithinSpeciality())
		{
			form.chkNonStandard().setEnabled(!form.chkIsDefault().getValue());
			if(form.chkIsDefault().getValue())
				form.chkNonStandard().setValue(false);
		}
		else
		{
			if (form.chkIsDefault().getValue())
			{
				form.chkNonStandard().setEnabled(false);
				form.chkNonStandard().setValue(false);
			}
			else
			{
				form.chkNonStandard().setEnabled(true);
				form.chkNonStandard().setValue(false);
			}
		}
		
	}

	@Override
	protected void onChkNonStandardValueChanged() throws PresentationLogicException 
	{
		if(form.getLocalContext().getAlreadyWithinSpecialityIsNotNull() &&
				!form.getLocalContext().getAlreadyWithinSpeciality())
		{
			form.chkIsDefault().setEnabled(!form.chkNonStandard().getValue());
			if(form.chkNonStandard().getValue())
				form.chkIsDefault().setValue(false);
		}
		else
		{
			if (form.chkNonStandard().getValue())
			{
				form.chkIsDefault().setEnabled(false);
				form.chkIsDefault().setValue(false);
			}
			else
			{
				form.chkIsDefault().setEnabled(true);
				form.chkIsDefault().setValue(false);
			}
		}
		
		
	}
}
