/FileExtraction/Java_unseen/IMS-MAXIMS_openMAXIMS/Source Library/openmaxims_workspace/Pathways/src/ims/pathways/forms/pathwaytargetconfigdialog/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.pathwaytargetconfigdialog;

import ims.core.vo.lookups.PreActiveActiveInactiveStatus;
import ims.core.vo.lookups.Specialty;
import ims.framework.enumerations.DialogResult;
import ims.framework.enumerations.FormMode;
import ims.framework.exceptions.CodingRuntimeException;
import ims.framework.exceptions.PresentationLogicException;
import ims.pathways.configuration.vo.ExternalEventMappingRefVoCollection;
import ims.pathways.forms.pathwaytargetconfigdialog.GenForm.lyrMappingsLayer.tabExternalContainer.grdEventsRow;
import ims.pathways.forms.pathwaytargetconfigdialog.GenForm.lyrMappingsLayer.tabRTTEventsContainer.grdRTTEventsRow;
import ims.pathways.forms.pathwaytargetconfigdialog.GenForm.ctnTargetSelectContainer.grdTargetsRow;
import ims.pathways.vo.EventTargetShortVo;
import ims.pathways.vo.EventTargetShortVoCollection;
import ims.pathways.vo.EventVo;
import ims.pathways.vo.ExternalEventMappingVo;
import ims.pathways.vo.ExternalEventMappingVoCollection;
import ims.pathways.vo.PathwayTargetExternalEventMappingVo;
import ims.pathways.vo.PathwayTargetExternalEventMappingVoCollection;
import ims.pathways.vo.PathwayTargetRTTEventVo;
import ims.pathways.vo.PathwayTargetRTTEventVoCollection;
import ims.pathways.vo.RTTEventVo;
import ims.pathways.vo.RTTEventVoCollection;
import ims.pathways.vo.TargetShortVo;
import ims.pathways.vo.TargetShortVoCollection;
import ims.pathways.vo.lookups.EventLinkType;

public class Logic extends BaseLogic
{
	private static final long	serialVersionUID	= 1L;

	protected void onFormOpen(Object[] args) throws ims.framework.exceptions.PresentationLogicException
	{
		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)
	{
		if(form.getGlobalContext().Pathways.getSelectedPathwaySpecialty() == null)
		{
			engine.showErrors(new String[] {"Specialty is mandatory"});
			engine.close(DialogResult.CANCEL);
			return;
		}
		
		form.setMode(mode);

		TargetShortVo voTarget = form.getGlobalContext().Pathways.getSelectedTarget();
		form.lyrMappings().tabExternal().cmbSpecialty().setValue(form.getGlobalContext().Pathways.getSelectedPathwaySpecialty());
		form.btnOk().setEnabled(false);
		if (voTarget != null)
		{
			if (voTarget.getID_TargetIsNotNull())
			{
				addTargetRow(voTarget);
				form.ctnTargetSelect().grdTargets().setValue(voTarget);
				grdTargetSelectionChanged();
				enableSearchControls(false);
			}
		}
		else
		{
			search();
		}

		if (mode.equals(FormMode.VIEW))
			enableSearchControls(false);

		updateSpecialtyComboState();
	}

	private void updateSpecialtyComboState()
	{
		if (form.getMode().equals(FormMode.EDIT))
		{
			form.lyrMappings().tabExternal().cmbSpecialty().setEnabled(form.ctnTargetSelect().grdTargets().getValue() != null);
		}
	}
	
	private void enableSearchControls(boolean isEnabled)
	{
		form.ctnTargetSelect().txtSearchName().setEnabled(isEnabled);
		form.ctnTargetSelect().cmbSearchEvent().setEnabled(isEnabled);
		form.ctnTargetSelect().imbSearch().setEnabled(isEnabled);
		form.ctnTargetSelect().imbClear().setEnabled(isEnabled);
	}

	private void clearScreen()
	{
		form.ctnTargetSelect().txtSearchName().setValue(null);
		form.ctnTargetSelect().cmbSearchEvent().setValue(null);
		form.ctnTargetSelect().grdTargets().getRows().clear();
		form.lyrMappings().tabExternal().grdEvents().getRows().clear();
		form.ctnTargetSelect().grdTargets().setFooterValue("Total records : 0");

	}

	protected void onImbClearClick() throws ims.framework.exceptions.PresentationLogicException
	{
		clearScreen();
	}

	protected void onImbSearchClick() throws ims.framework.exceptions.PresentationLogicException
	{
		search();
	}

	private void search()
	{
		form.ctnTargetSelect().grdTargets().getRows().clear();

		TargetShortVoCollection voCollTarget = domain.listTargetByCriteria(form.ctnTargetSelect().txtSearchName().getValue(), form.ctnTargetSelect().cmbSearchEvent().getValue());

		populateTargetGridFromData(voCollTarget);
	}

	private void populateTargetGridFromData(TargetShortVoCollection voCollTarget)
	{
		if (voCollTarget == null || voCollTarget.size() == 0)
		{
			engine.showMessage("No matching records found");
			form.ctnTargetSelect().grdTargets().setFooterValue("Total records : 0");
			return;
		}

		for (int i = 0; i < voCollTarget.size(); i++)
		{
			TargetShortVo voTarget = voCollTarget.get(i);

			if (!isTargetSelected(voTarget))
				addTargetRow(voTarget);
		}

		form.ctnTargetSelect().grdTargets().setFooterValue("Total records : " + form.ctnTargetSelect().grdTargets().getRows().size());
		if (form.ctnTargetSelect().grdTargets().getRows().size() == 0)
		{
			engine.showMessage("All Targets for the search criteria already configured.");
			return;
		}
	}

	private boolean isTargetSelected(TargetShortVo voTarget)
	{
		if (voTarget == null || form.getGlobalContext().Pathways.getSelectedTargets() == null)
			return false;

		return form.getGlobalContext().Pathways.getSelectedTargets().contains(voTarget);
	}

	private void addTargetRow(TargetShortVo voTarget)
	{
		grdTargetsRow row = form.ctnTargetSelect().grdTargets().getRows().newRow();
		row.setColName(voTarget.getName());
		row.setTooltipForColName(voTarget.getName());

		row.setColDescr(voTarget.getDescription());
		row.setTooltipForColDescr(voTarget.getDescription());

		row.setColEventLink(voTarget.getEventLinkType().toString());
		row.setTooltipForColEventLink(voTarget.getEventLinkType().toString());

		row.setColStatus(voTarget.getStatus().toString());
		row.setTooltipForColStatus(voTarget.getStatus().toString());

		row.setValue(voTarget);
	}

	protected void onBtnOkClick() throws ims.framework.exceptions.PresentationLogicException
	{
		if (form.getMode().equals(FormMode.EDIT))
		{
			populateSelectedMappings();
			form.getGlobalContext().Pathways.setSelectedTarget(form.ctnTargetSelect().grdTargets().getValue());
			engine.close(DialogResult.OK);
			return;
		}
		engine.close(DialogResult.CANCEL);
	}

	private void populateSelectedMappings()
	{
		PathwayTargetExternalEventMappingVoCollection voCollExternalMappings = form.getGlobalContext().Pathways.getSelectedPathwayTargetExternalMappings();
		if (voCollExternalMappings == null)
			voCollExternalMappings = new PathwayTargetExternalEventMappingVoCollection();

		for (int i = 0; i < form.lyrMappings().tabExternal().grdEvents().getRows().size(); i++)
		{
			grdEventsRow eRow = form.lyrMappings().tabExternal().grdEvents().getRows().get(i);
			if (eRow.getRows().size() > 0)
			{
				for (int p = 0; p < eRow.getRows().size(); p++)
				{
					grdEventsRow cRow = eRow.getRows().get(p);
					if (cRow.getColSelect())
						voCollExternalMappings.add(createOrGetMapping(cRow));
					else
					{
						// if the mapping has now become available while editing
						// the Pathway record
						if (!cRow.isColSelectReadOnly())
						{
							updateOrRemoveMapping(voCollExternalMappings, cRow);
							removeMappingForTargetFromGlobalContext(cRow.getValue(), form.getGlobalContext().Pathways.getSelectedTarget());
						}
					}
				}
			}
		}

		form.getGlobalContext().Pathways.setSelectedPathwayTargetExternalMappings(voCollExternalMappings);

		PathwayTargetRTTEventVoCollection voCollRTTMappings = form.getGlobalContext().Pathways.getSelectedPathwayTargetRTTEvents();
		if (voCollRTTMappings == null)
			voCollRTTMappings = new PathwayTargetRTTEventVoCollection();

		voCollRTTMappings.clear();

		for (int i = 0; i < form.lyrMappings().tabRTTEvents().grdRTTEvents().getRows().size(); i++)
		{
			grdRTTEventsRow rRow = form.lyrMappings().tabRTTEvents().grdRTTEvents().getRows().get(i);
			if (rRow.getRows().size() > 0)
			{
				for (int p = 0; p < rRow.getRows().size(); p++)
				{
					grdRTTEventsRow cRow = rRow.getRows().get(p);
					if (cRow.getColSelect())
						voCollRTTMappings.add(createOrGetMapping(cRow));
					else
					{
						// if the mapping has now become available while editing
						// the Pathway record
						if (!cRow.isColSelectReadOnly())
						{
							if (form.getGlobalContext().Pathways.getSelectedPathwayTargetsRTTEventsIsNotNull() && form.getGlobalContext().Pathways.getSelectedPathwayTargetsRTTEvents().contains(createOrGetMapping(cRow)))
								form.getGlobalContext().Pathways.getSelectedPathwayTargetsRTTEvents().remove(createOrGetMapping(cRow));
						}
					}
				}
			}
		}

		form.getGlobalContext().Pathways.setSelectedPathwayTargetRTTEvents(voCollRTTMappings);
	}

	private void updateOrRemoveMapping(PathwayTargetExternalEventMappingVoCollection voCollExternalMappings, grdEventsRow row)
	{
		PathwayTargetExternalEventMappingVo mapping = createOrGetMapping(row);
		if(mapping != null && mapping.getPathwayTarget() == null)
			voCollExternalMappings.remove(mapping);
	}

	private void removeMappingForTargetFromGlobalContext(ExternalEventMappingVo value, TargetShortVo selectedTarget)
	{
		PathwayTargetExternalEventMappingVoCollection mappings = form.getGlobalContext().Pathways.getSelectedPathwayTargetsExternalMappings();
		if(mappings == null || mappings.size() == 0)
			return;
		
		PathwayTargetExternalEventMappingVo item = null;
		boolean remove = false;
		for(int i=0;i<mappings.size();i++)
		{
			item = mappings.get(i);
			if(item.getExternalEventMapping().equals(value))
			{
				remove = true;
				break;
			}
		}
		
		if(remove)
			form.getGlobalContext().Pathways.getSelectedPathwayTargetsExternalMappings().remove(item);
	}

	private PathwayTargetRTTEventVo createOrGetMapping(grdRTTEventsRow row)
	{
		
		PathwayTargetRTTEventVoCollection ptRTTMappings = form.getGlobalContext().Pathways.getSelectedPathwayTargetsRTTEvents();

		PathwayTargetRTTEventVo mappingToRemove = null;
		if (ptRTTMappings != null)
		{
			for (int i = 0; i < ptRTTMappings.size(); i++)
			{
				PathwayTargetRTTEventVo ptRTTMapping = ptRTTMappings.get(i);
				if (ptRTTMapping.getRTTEvent().equals(row.getValue()))
				{
					if(!row.getColSelect() && ptRTTMapping.getID_PathwayTargetRTTEventIsNotNull())
					{
						ptRTTMapping.setStatus(PreActiveActiveInactiveStatus.INACTIVE);
						return ptRTTMapping;
					}
					else if(row.getColSelect())
					{
						//reactivating a record inactivated within the current session that has not yet been saved
						if(ptRTTMapping.getID_PathwayTargetRTTEventIsNotNull())
							ptRTTMapping.setStatus(PreActiveActiveInactiveStatus.ACTIVE);
						return ptRTTMapping;
					}
					else
					{
						mappingToRemove = ptRTTMapping;
						break;
					}	
				}
					
			}
		}

		PathwayTargetRTTEventVo ptRTTMapping = null;
		if(row.getColSelect())
		{
			ptRTTMapping = new PathwayTargetRTTEventVo();
			ptRTTMapping.setRTTEvent(row.getValue());
		}
		
		if(mappingToRemove != null)
			return mappingToRemove;

		return ptRTTMapping;
		
		//////////////////////
		
//		PathwayTargetRTTEventVoCollection ptRTTMappings = form.getGlobalContext().Pathways.getSelectedPathwayTargetsRTTEvents();
//
//		if (ptRTTMappings != null)
//		{
//			for (int i = 0; i < ptRTTMappings.size(); i++)
//			{
//				PathwayTargetRTTEventVo ptRttMapping = ptRTTMappings.get(i);
//				if (ptRttMapping.getRTTEvent().equals(row.getValue()))
//				{
//					if(!row.getColSelect() && ptRttMapping.getID_PathwayTargetRTTEventIsNotNull())
//						ptRttMapping.setStatus(PreActiveActiveInactiveStatus.INACTIVE);
//					else if(row.getColSelect())
//						return ptRttMapping;
//					
//					return null;
//				}	
//			}
//		}
//
//		PathwayTargetRTTEventVo ptRTTEvent = new PathwayTargetRTTEventVo();
//		ptRTTEvent.setRTTEvent(row.getValue());
//
//		return ptRTTEvent;
	}

	private PathwayTargetExternalEventMappingVo createOrGetMapping(grdEventsRow row)
	{
		PathwayTargetExternalEventMappingVoCollection ptExMappings = form.getGlobalContext().Pathways.getSelectedPathwayTargetsExternalMappings();

		PathwayTargetExternalEventMappingVo mappingToRemove = null;
		if (ptExMappings != null)
		{
			for (int i = 0; i < ptExMappings.size(); i++)
			{
				PathwayTargetExternalEventMappingVo ptExMapping = ptExMappings.get(i);
				if (ptExMapping.getExternalEventMapping().equals(row.getValue()))
				{
					if(!row.getColSelect() && ptExMapping.getID_PathwayTargetExternalEventMappingIsNotNull())
					{
						ptExMapping.setStatus(PreActiveActiveInactiveStatus.INACTIVE);
						return ptExMapping;
					}
					else if(row.getColSelect())
					{
						//reactivating a record inactivated within the current session that has not yet been saved
						if(ptExMapping.getID_PathwayTargetExternalEventMappingIsNotNull())
							ptExMapping.setStatus(PreActiveActiveInactiveStatus.ACTIVE);
						return ptExMapping;
					}
					else
					{
						mappingToRemove = ptExMapping;
						break;
					}	
				}
					
			}
		}

		PathwayTargetExternalEventMappingVo ptExMapping = null;
		if(row.getColSelect())
		{
			ptExMapping = new PathwayTargetExternalEventMappingVo();
			ptExMapping.setExternalEventMapping(row.getValue());
		}
		
		if(mappingToRemove != null)
			return mappingToRemove;

		return ptExMapping;
	}

	protected void onBtnCancelClick() throws ims.framework.exceptions.PresentationLogicException
	{
		engine.close(DialogResult.CANCEL);
	}

	protected void onGrdTargetsSelectionChanged() throws PresentationLogicException
	{
		grdTargetSelectionChanged();
	}

	private void grdTargetSelectionChanged()
	{
		if (form.ctnTargetSelect().grdTargets().getValue() == null)
			throw new CodingRuntimeException("Target must be selected");

		enableSearchControls(false);

		EventLinkType linkType = form.ctnTargetSelect().grdTargets().getValue().getEventLinkType();
		if (linkType.equals(EventLinkType.MANUAL))
		{
			form.lyrMappings().hide();
			form.lyrMappings().tabExternal().grdEvents().getRows().clear();
			form.lyrMappings().tabRTTEvents().grdRTTEvents().getRows().clear();
			form.lblMapping().setVisible(false);
		}
		else
		{
			form.lyrMappings().tabRTTEvents().setVisible(true);
			form.lyrMappings().tabExternal().setVisible(true);
			form.lyrMappings().showtabExternal();
			form.lblMapping().setVisible(true);

			EventTargetShortVoCollection voCollEventTarget = domain.listEventTargetByTarget(form.ctnTargetSelect().grdTargets().getValue(), form.getMode().equals(FormMode.VIEW));
			form.getLocalContext().setSelectedEventTargets(voCollEventTarget);

			populateExternalEventMappingsGrid(voCollEventTarget, form.lyrMappings().tabExternal().cmbSpecialty().getValue(), false);
			populateRTTEventMappingsGrid(voCollEventTarget);
		}

		form.btnOk().setEnabled(form.ctnTargetSelect().grdTargets().getSelectedRow() != null);
		updateSpecialtyComboState();
	}

	private void populateRTTEventMappingsGrid(EventTargetShortVoCollection voCollEventTarget)
	{
		form.lyrMappings().tabRTTEvents().grdRTTEvents().getRows().clear();

		if (voCollEventTarget != null)
		{
			// filter eventtarget mappings coll to exclude mappings already used
			// for this pathway
			PathwayTargetRTTEventVoCollection pathwayRTTMappings = form.getGlobalContext().Pathways.getSelectedPathwayTargetsRTTEvents();

			for (int i = 0; i < voCollEventTarget.size(); i++)
			{
				EventTargetShortVo voEvTarget = voCollEventTarget.get(i);

				// only add events that have RTT mappings that will be
				// selectable
				if (voEvTarget.getEvent() == null)
					continue;

				grdRTTEventsRow rRow = form.lyrMappings().tabRTTEvents().grdRTTEvents().getRows().newRow();
				rRow.setExpanded(true);
				EventVo voEvent = voEvTarget.getEvent();
				if (voEvent != null)
				{
					rRow.setColName(voEvent);
					rRow.setTooltip(voEvent  != null ? voEvent.getName() : null);
					RTTEventVoCollection voCollRTTMappings = domain.getRTTByEventAndStatus(voEvent, PreActiveActiveInactiveStatus.ACTIVE);
					if (voCollRTTMappings != null)
					{
						for (int p = 0; p < voCollRTTMappings.size(); p++)
						{
							RTTEventVo voRTTEventMapping = voCollRTTMappings.get(p);
							if (voRTTEventMapping != null)
							{
								boolean selectedForTarget = isMappingSelectedForPathwayTarget(voRTTEventMapping);

								grdRTTEventsRow childRow = rRow.getRows().newRow();
								if (voRTTEventMapping.getProviderSystemIsNotNull())
								{
									childRow.setColProvider(voRTTEventMapping.getProviderSystem().getSystemName());
									childRow.setTooltip(voRTTEventMapping.getProviderSystem().getSystemName());
								}
								if (voRTTEventMapping.getActionIsNotNull())
								{			
									childRow.setColAction(voRTTEventMapping.getAction().getText());									
									childRow.setTooltipForColAction(voRTTEventMapping.getAction().getText());
								}

								childRow.setColNatCode(voRTTEventMapping.getNationalCode());
								childRow.setTooltipForColNatCode(voRTTEventMapping.getNationalCode());

								childRow.setColPasCode(voRTTEventMapping.getPASCode());
								childRow.setTooltipForColPasCode(voRTTEventMapping.getPASCode());

								childRow.setColSelectReadOnly(false);
								childRow.setColSelect(selectedForTarget);

								if (childRow.getColSelect() == false)
								{
									if (isExternalMappingAlreadyUsedForPathway(voRTTEventMapping, pathwayRTTMappings))
									{
										childRow.setColSelectReadOnly(true);
										childRow.setTooltipForColSelect(form.getMode().equals(FormMode.EDIT) ? "This mapping has already been configured for this Pathway" : "");
									}
								}
								childRow.setValue(voRTTEventMapping);
							}
						}
					}
				}
			}
			
			for (int j = form.lyrMappings().tabRTTEvents().grdRTTEvents().getRows().size(); j > 0; j--)
			{
				grdRTTEventsRow row = form.lyrMappings().tabRTTEvents().grdRTTEvents().getRows().get(j - 1);
				if (row.getRows().size() == 0)
					form.lyrMappings().tabRTTEvents().grdRTTEvents().getRows().remove(j - 1);
			}
		}
	}

	private boolean isExternalMappingAlreadyUsedForPathway(RTTEventVo voRTTEventMapping, PathwayTargetRTTEventVoCollection pathwayRTTMappings)
	{
		if(pathwayRTTMappings != null)
		{
			for (int i = 0; i < pathwayRTTMappings.size(); i++)
			{
				PathwayTargetRTTEventVo mapping = pathwayRTTMappings.get(i);
				if (mapping.getRTTEventIsNotNull()&&mapping.getStatusIsNotNull()&&mapping.getPathwayTargetIsNotNull()&&mapping.getPathwayTarget().getStatusIsNotNull())
					if (mapping.getRTTEvent().equals(voRTTEventMapping)  && mapping.getStatus().equals(PreActiveActiveInactiveStatus.ACTIVE) && mapping.getPathwayTarget().getStatus().equals(PreActiveActiveInactiveStatus.ACTIVE))
						return true;
			}			
		}
		return false;
	}

	/**
	 * 
	 * check the GC and if mapping is found return true
	 * 
	 * @param voRTTEventMapping
	 */
	private boolean isMappingSelectedForPathwayTarget(RTTEventVo voRTTEventMapping)
	{
		if (form.getGlobalContext().Pathways.getSelectedPathwayTargetRTTEventsIsNotNull())
		{
			for (int i = 0; i < form.getGlobalContext().Pathways.getSelectedPathwayTargetRTTEvents().size(); i++)
			{
				PathwayTargetRTTEventVo mapping = form.getGlobalContext().Pathways.getSelectedPathwayTargetRTTEvents().get(i);
				if (mapping.getRTTEvent().equals(voRTTEventMapping))
					return true;
			}
		}

		return false;
	}

	/**
	 * @desc This method looks after showing available mappings,showing selected
	 *       mappings and filtering available list by specialty
	 * @param voCollEventTarget
	 * @param specialty
	 * @param bFiredFromComboSelectionChanged
	 */
	private void populateExternalEventMappingsGrid(EventTargetShortVoCollection voCollEventTarget, Specialty specialty, boolean isFiredFromComboSelectionChanged)
	{
		// if this method has been called from the specialty combo selection
		// change get a list of what was selected hold it and reselect it
		ExternalEventMappingRefVoCollection locallySelectedMappings = null;
		if (isFiredFromComboSelectionChanged)
		{
			locallySelectedMappings = new ExternalEventMappingRefVoCollection();
			for (int i = 0; i < form.lyrMappings().tabExternal().grdEvents().getRows().size(); i++)
			{
				grdEventsRow pRow = form.lyrMappings().tabExternal().grdEvents().getRows().get(i);
				for (int p = 0; p < pRow.getRows().size(); p++)
				{
					grdEventsRow cRow = pRow.getRows().get(p);
					if (cRow.getColSelect() && getMappingSelectedForPathwayTarget(cRow.getValue()) == null)
						locallySelectedMappings.add(cRow.getValue());
				}
			}
		}

		form.lyrMappings().tabExternal().grdEvents().getRows().clear();

		if (voCollEventTarget != null)
		{
			// filter eventtarget mappings coll to exclude mappings already used
			// for this pathway
			PathwayTargetExternalEventMappingVoCollection pathwayExternalMappings = form.getGlobalContext().Pathways.getSelectedPathwayTargetsExternalMappings();

			for (int i = 0; i < voCollEventTarget.size(); i++)
			{
				EventTargetShortVo voEvTarget = voCollEventTarget.get(i);

				// only add events that have mappings that will be selectable
				if (voEvTarget.getEvent() == null)
					continue;

				grdEventsRow eRow = form.lyrMappings().tabExternal().grdEvents().getRows().newRow();
				EventVo voEvent = voEvTarget.getEvent();
				if (voEvent != null)
				{
					eRow.setColName(voEvent);
					eRow.setTooltipForColName(voEvent.toString());

					eRow.setExpanded(true);
					ExternalEventMappingVoCollection voCollEventMappings = domain.getEventMappingsByEventAndStatus(voEvent, PreActiveActiveInactiveStatus.ACTIVE);
					if (voCollEventMappings != null)
					{
						grdEventsRow childRow = null;
						for (int p = 0; p < voCollEventMappings.size(); p++)
						{
							ExternalEventMappingVo voEventMapping = voCollEventMappings.get(p);
							if (voEventMapping != null)
							{
								PathwayTargetExternalEventMappingVo mapping = getMappingSelectedForPathwayTarget(voEventMapping);
								boolean selectedForTarget = mapping != null;
								boolean selectedLocally = locallySelectedMappings != null && locallySelectedMappings.contains(voEventMapping);
								boolean displayMappingRow = true;
								if (specialty != null && voEventMapping.getSpecialtyIsNotNull())
									displayMappingRow = voEventMapping.getSpecialty().equals(specialty);

								if (!displayMappingRow && !selectedLocally && !selectedForTarget)
									continue;

								childRow = eRow.getRows().newRow();
								if(selectedForTarget)
									childRow.setColPtExMapping(mapping);
									
								if (voEventMapping.getProviderSystemIsNotNull())
								{
									childRow.setColProvider(voEventMapping.getProviderSystem().getSystemName());
									childRow.setTooltipForColProvider(voEventMapping.getProviderSystem().getSystemName());
								}
								childRow.setColClinicCode(voEventMapping.getClinicCode());
								childRow.setTooltipForColClinicCode(voEventMapping.getClinicCode());

								if (voEventMapping.getConsultantIsNotNull())
								{
									childRow.setColConsultant(voEventMapping.getConsultant().toString());
									childRow.setTooltipForColConsultant(voEventMapping.getConsultant().toString());
								}

								childRow.setColDescr(voEventMapping.getDescription());
								childRow.setTooltipForColDescr(voEventMapping.getDescription());

								if (voEventMapping.getGroupIsNotNull())
								{
									childRow.setColGroup(voEventMapping.getGroup().getText());
									childRow.setTooltipForColGroup(voEventMapping.getGroup().getText());
								}

								if (voEventMapping.getDetailIsNotNull())
								{
									childRow.setColDetail(voEventMapping.getDetail().getText());
									childRow.setTooltipForColDetail(voEventMapping.getDetail().getText());
								}

								if (voEventMapping.getSpecialtyIsNotNull())
								{
									childRow.setColSpecialty(voEventMapping.getSpecialty().getText());
									childRow.setTooltipForColSpecialty(voEventMapping.getSpecialty().getText());
								}
								childRow.setColSelectReadOnly(false);
								childRow.setColSelect(selectedForTarget || selectedLocally );
								if(mapping != null && (mapping.getStatus() != null && mapping.getStatus().equals(PreActiveActiveInactiveStatus.INACTIVE)))
									childRow.setColSelect(false);
	
								if (childRow.getColSelect() == false)
								{
									if (isExternalMappingAlreadyUsedForPathway(voEventMapping, pathwayExternalMappings))
									{
										childRow.setColSelectReadOnly(true);
										childRow.setTooltipForColSelect(form.getMode().equals(FormMode.EDIT) ? "This mapping has already been configured for this Pathway" : "");
									}
								}

								childRow.setValue(voEventMapping);
							}
						}
					}
				}
			}

			for (int j = form.lyrMappings().tabExternal().grdEvents().getRows().size(); j > 0; j--)
			{
				grdEventsRow row = form.lyrMappings().tabExternal().grdEvents().getRows().get(j - 1);
				if (row.getRows().size() == 0)
					form.lyrMappings().tabExternal().grdEvents().getRows().remove(j - 1);
			}
		}
	}

	private boolean isExternalMappingAlreadyUsedForPathway(ExternalEventMappingVo voEventMapping, PathwayTargetExternalEventMappingVoCollection pathwayExternalMappings)
	{
		if (pathwayExternalMappings != null)
		{
			for (int i = 0; i < pathwayExternalMappings.size(); i++)
			{
				PathwayTargetExternalEventMappingVo mapping = pathwayExternalMappings.get(i);
				if(mapping.getExternalEventMappingIsNotNull()&&mapping.getStatusIsNotNull()&&mapping.getPathwayTargetIsNotNull()&&mapping.getPathwayTarget().getStatusIsNotNull())
					if (mapping.getExternalEventMapping().equals(voEventMapping) && !mapping.getStatus().equals(PreActiveActiveInactiveStatus.INACTIVE) && mapping.getPathwayTarget().getStatus().equals(PreActiveActiveInactiveStatus.ACTIVE))
						return true;
			}
		}

		return false;
	}

	/**
	 * 
	 * check the GC and if mapping is found for this target return true
	 * 
	 * @param voEventMapping
	 */
	private PathwayTargetExternalEventMappingVo getMappingSelectedForPathwayTarget(ExternalEventMappingVo voEventMapping)
	{
		if (form.getGlobalContext().Pathways.getSelectedPathwayTargetExternalMappingsIsNotNull())
		{
			for (int i = 0; i < form.getGlobalContext().Pathways.getSelectedPathwayTargetExternalMappings().size(); i++)
			{
				PathwayTargetExternalEventMappingVo mapping = form.getGlobalContext().Pathways.getSelectedPathwayTargetExternalMappings().get(i);
				if (mapping.getExternalEventMapping().equals(voEventMapping))
					return mapping;
			}
		}

		return null;
	}

	protected void onCmbSpecialtyValueChanged() throws PresentationLogicException
	{
		if (form.ctnTargetSelect().grdTargets().getValue() != null)
			applySpecialtyFilter(form.lyrMappings().tabExternal().cmbSpecialty().getValue());
	}

	/**
	 * @desc filter displayed mappings by specialty (ie remove non-selected
	 *       items that are not for this specialty)
	 * @param value
	 */
	private void applySpecialtyFilter(Specialty value)
	{
		populateExternalEventMappingsGrid(form.getLocalContext().getSelectedEventTargets(), value, true);
	}
}
