/FileExtraction/Java_unseen/IMS-MAXIMS_openMAXIMS/Source Library/openmaxims_workspace/Pathways/src/ims/pathways/forms/entityeventmap/Logic.java
//#############################################################################
//#                                                                           #
//#  Copyright (C) <2015>  <IMS MAXIMS>                                       #
//#                                                                           #
//#  This program is free software: you can redistribute it and/or modify     #
//#  it under the terms of the GNU Affero General Public License as           #
//#  published by the Free Software Foundation, either version 3 of the       #
//#  License, or (at your option) any later version.                          # 
//#                                                                           #
//#  This program is distributed in the hope that it will be useful,          #
//#  but WITHOUT ANY WARRANTY; without even the implied warranty of           #
//#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the            #
//#  GNU Affero General Public License for more details.                      #
//#                                                                           #
//#  You should have received a copy of the GNU Affero General Public License #
//#  along with this program.  If not, see <http://www.gnu.org/licenses/>.    #
//#                                                                           #
//#  IMS MAXIMS provides absolutely NO GUARANTEE OF THE CLINICAL SAFTEY of    #
//#  this program.  Users of this software do so entirely at their own risk.  #
//#  IMS MAXIMS only ensures the Clinical Safety of unaltered run-time        #
//#  software that it builds, deploys and maintains.                          #
//#                                                                           #
//#############################################################################
//#EOH
// This code was generated by Mara Iroaie using IMS Development Environment (version 1.80 build 5003.20929)
// Copyright (C) 1995-2013 IMS MAXIMS. All rights reserved.

package ims.pathways.forms.entityeventmap;

import java.util.ArrayList;
import java.util.Comparator;


import ims.configuration.gen.ConfigFlag;
import ims.domain.exceptions.StaleObjectException;
import ims.framework.enumerations.FormMode;

import ims.framework.exceptions.PresentationLogicException;

import ims.pathways.forms.entityeventmap.GenForm.grdMappingsRow;
import ims.pathways.vo.EventLiteVoCollection;
import ims.pathways.vo.PathwayEntityEventMapVo;
import ims.pathways.vo.PathwayEntityEventMapVoCollection;

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

	@Override
	protected void onFormOpen(Object[] args) throws ims.framework.exceptions.PresentationLogicException
	{
		initialize();
		open();
	}
	
	private void open()
	{
		populateGrid(domain.listPathwayEntityEvents());
		form.grdMappings().setValue(form.getLocalContext().getselectedEntity());
		populateScreenFromData(form.grdMappings().getValue());
		form.setMode(FormMode.VIEW);	
	}
	
	private void initialize()
	{		
		loadBOs();
	}

	private void loadBOs()
	{
		String[] boList = domain.listBOEntities();
		java.util.Arrays.sort(boList, new stringComparator());
		form.getLocalContext().setBOEntities(boList);
	}

	private void populateGrid(PathwayEntityEventMapVoCollection records)
	{
		form.grdMappings().getRows().clear();
		
		for (int i=0; i< records.size(); i++)
		{
			addPathwayEntityEventGridLine(records.get(i));
		}
	}
	private void addPathwayEntityEventGridLine(PathwayEntityEventMapVo pathwayEntityEventMapVo)
	{
		grdMappingsRow newLine = form.grdMappings().getRows().newRow();
		
		newLine.setcolEntityName(pathwayEntityEventMapVo.getEntity());
		newLine.setCellcolEntityNameTooltip(newLine.getcolEntityName());
		if (pathwayEntityEventMapVo.getEvent() != null)
		{
    		newLine.setcolEvent(pathwayEntityEventMapVo.getEvent().getName());
    		newLine.setCellcolEventTooltip(newLine.getcolEvent());
		}
		else
		{
    		newLine.setcolEvent(null);
    		newLine.setCellcolEventTooltip(null);			
		}
		newLine.setcolDescription(pathwayEntityEventMapVo.getDescription());
		newLine.setCellcolDescriptionTooltip(newLine.getcolDescription());
		newLine.setcolRule(pathwayEntityEventMapVo.getRule());
		newLine.setCellcolRuleTooltip(newLine.getcolRule());
		newLine.setcolTargetMethod(pathwayEntityEventMapVo.getTargetMethod());
		newLine.setCellcolTargetMethodTooltip(newLine.getcolTargetMethod());
		if (pathwayEntityEventMapVo.getScheduledDateTimeField() != null)
		{
			newLine.setColSchDateTime(pathwayEntityEventMapVo.getScheduledDateTimeField().toString());
			newLine.setCellColSchDateTimeTooltip(newLine.getColSchDateTime());
		}
		newLine.setcolActive(pathwayEntityEventMapVo.getActive());
		
		newLine.setValue(pathwayEntityEventMapVo);	
	}

	protected void onBtnNewClick() throws ims.framework.exceptions.PresentationLogicException
	{
		newInstance();
	}
	
	private void newInstance()
	{
		form.getLocalContext().setselectedEntity(null);
		clearInstanceConctrols();
		form.setMode(FormMode.EDIT);
	}

	private void clearInstanceConctrols()
	{
		form.ctnEntityDetails().qmbEntity().clear();
		form.ctnEntityDetails().qmbEvents().clear();
		form.ctnEntityDetails().txtScheduledDateTime().setValue(null);
		form.ctnEntityDetails().txtRule().setValue(null);
		form.ctnEntityDetails().txtDescription().setValue(null);
		form.ctnEntityDetails().chkIsActive().setValue(true);		
	}

	protected void onQmbEventsTextSubmited(String value) throws ims.framework.exceptions.PresentationLogicException
	{		
		eventsSearch(value);
	}
	
	private void eventsSearch(String value)
	{
		EventLiteVoCollection eventsList = domain.listEvents(value);
		populateEventCombo(eventsList);
	}

	private void populateEventCombo(EventLiteVoCollection eventsList)
	{
		form.ctnEntityDetails().qmbEvents().clear();
		for (int i = 0; i < eventsList.size(); i++)
		{
			form.ctnEntityDetails().qmbEvents().newRow(eventsList.get(i), eventsList.get(i).getName());
		}
		
		if(eventsList.size() == 1)
			form.ctnEntityDetails().qmbEvents().setValue(eventsList.get(0));
		else
		{
			form.ctnEntityDetails().qmbEvents().setValue(null);
			form.ctnEntityDetails().qmbEvents().showOpened();
		}
	}

	protected void onBtnEditClick() throws ims.framework.exceptions.PresentationLogicException
	{
		editInstance();
	}
	
	private void editInstance()
	{
		form.setMode(FormMode.EDIT);	
	}

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

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

	private boolean save()
	{	
		PathwayEntityEventMapVo entityToBeSaved = populateDataFromScreen();
		
		String[] validationError =entityToBeSaved.validate(validateUiRules());
		
		if (validationError != null && validationError.length > 0)
		{
			engine.showErrors(validationError);
			return false;
		}
		
		try
		{
			form.getLocalContext().setselectedEntity(domain.savePathwayEntity(entityToBeSaved));
			return true;
		}
		catch (StaleObjectException err)
		{
			form.getLocalContext().setselectedEntity(null);
			engine.showMessage(err.getMessage());
			open();
			return false;
		}
	}

	private String[] validateUiRules()
	{
		ArrayList<String> errors = new ArrayList<String>();
		
		if (form.ctnEntityDetails().qmbEntity().getValue() == null)
			errors.add("Entity Name is Mandatory");
//		if (form.ctnEntityDetails().qmbEvents().getValue() == null)
//			errors.add("Event is Mandatory");
			
		if (errors.size() > 0)
		{
			String[] validationErrors = new String[errors.size()];
			errors.toArray(validationErrors);
			return validationErrors;
		}
		
		return null;
	}

	private PathwayEntityEventMapVo populateDataFromScreen()
	{
		PathwayEntityEventMapVo recodToSave = null;
		if (form.getLocalContext().getselectedEntity() != null)
			recodToSave = (PathwayEntityEventMapVo) form.getLocalContext().getselectedEntity().clone();
		else
			recodToSave = new PathwayEntityEventMapVo();
		
		recodToSave.setActive(form.ctnEntityDetails().chkIsActive().getValue());
		recodToSave.setEntity(form.ctnEntityDetails().qmbEntity().getValue());
		if (form.ctnEntityDetails().qmbEvents().getValue() != null)
			recodToSave.setEventId(form.ctnEntityDetails().qmbEvents().getValue().getID_Event());
		else
		{
			recodToSave.setEvent(null);
			recodToSave.setEventId(null);
		}
		recodToSave.setRule(form.ctnEntityDetails().txtRule().getValue());
		recodToSave.setDescription(form.ctnEntityDetails().txtDescription().getValue());
		recodToSave.setScheduledDateTimeField(form.ctnEntityDetails().txtScheduledDateTime().getValue());
		recodToSave.setTargetMethod(form.ctnEntityDetails().txtTargetMethod().getValue());
		
		return recodToSave;
	}

	protected void onGrdMappingsSelectionChanged()
	{
		form.getLocalContext().setselectedEntity(form.grdMappings().getValue());
		populateScreenFromData(form.getLocalContext().getselectedEntity());
		updateControlState();
	}

	private void populateScreenFromData(PathwayEntityEventMapVo getselectedEntity)
	{
		clearInstanceConctrols();
		
		if (getselectedEntity != null)
		{
    		form.ctnEntityDetails().qmbEntity().newRow(getselectedEntity.getEntity(), getselectedEntity.getEntity());
    		form.ctnEntityDetails().qmbEntity().setValue(getselectedEntity.getEntity());
    		if (getselectedEntity.getEvent() != null)
    		{
        		form.ctnEntityDetails().qmbEvents().newRow(getselectedEntity.getEvent(), getselectedEntity.getEvent().getName());
        		form.ctnEntityDetails().qmbEvents().setValue(getselectedEntity.getEvent());
    		}
    		else
    		{
        		form.ctnEntityDetails().qmbEvents().setValue(getselectedEntity.getEvent());
    		}	
    		form.ctnEntityDetails().txtScheduledDateTime().setValue(getselectedEntity.getScheduledDateTimeField());
    		form.ctnEntityDetails().txtRule().setValue(getselectedEntity.getRule());
    		form.ctnEntityDetails().txtDescription().setValue(getselectedEntity.getDescription());
    		form.ctnEntityDetails().chkIsActive().setValue(getselectedEntity.getActive());
    		form.ctnEntityDetails().txtTargetMethod().setValue(getselectedEntity.getTargetMethod());
		}
	}

	protected void onContextMenuItemClick(int menuItemID, ims.framework.Control sender) throws ims.framework.exceptions.PresentationLogicException
	{
		switch(menuItemID)
		{
			case GenForm.ContextMenus.GenericGrid.Add:
				newInstance();
				break;
			case GenForm.ContextMenus.GenericGrid.Update:
				editInstance();
				break;
		}
	}

	protected void onQmbEntityTextSubmited(String value) throws PresentationLogicException
	{
		entitiesSearch(value);	
	}

	private void entitiesSearch(String value)
	{
		int nrOfBo = form.getLocalContext().getBOEntities().length;
		ArrayList<String> boSearchList = new ArrayList<String>();
		String[] boSearchListNames = null;
		
		for(int i = 0; i <nrOfBo; i++)
		{
		//	if(value != null && form.getLocalContext().getBOEntities()[i] != null)
		//	{
    			if (value.startsWith("%"))				
    			{
    				boSearchList.add(form.getLocalContext().getBOEntities()[i]);
    			}
    			else if (form.getLocalContext().getBOEntities()[i].toUpperCase().contains(value.toUpperCase()))
    			{
    				boSearchList.add(form.getLocalContext().getBOEntities()[i]);
    			}
		//	}
		}	

		if (boSearchList != null && boSearchList.size() > 0)
		{
			boSearchListNames = new String[boSearchList.size()];
			boSearchList.toArray(boSearchListNames);
		}
		
		populateEntitiesCombo(boSearchListNames);
	}

	private void populateEntitiesCombo(String[] boSearchListNames)
	{
		form.ctnEntityDetails().qmbEntity().clear();
		if (boSearchListNames != null && boSearchListNames.length > 0)
		{
			for(int i = 0; i<boSearchListNames.length; i ++ )
			{
				form.ctnEntityDetails().qmbEntity().newRow(boSearchListNames[i], boSearchListNames[i]);
			}
			
			if (boSearchListNames.length == 1)
				form.ctnEntityDetails().qmbEntity().setValue(boSearchListNames[0]);
			else
			{
				form.ctnEntityDetails().qmbEntity().setValue(null);
				form.ctnEntityDetails().qmbEntity().showOpened();
			}	
		}
		else
			form.ctnEntityDetails().qmbEntity().showOpened();
			
	}

	protected void onFormModeChanged()
	{
		updateControlState();	
	}

	private void updateControlState()
	{
		form.ctnEntityDetails().setCollapsed(!(FormMode.EDIT.equals(form.getMode()) || form.grdMappings().getValue() != null));
		if (FormMode.VIEW.equals(form.getMode()))
		{
			form.btnEdit().setVisible(form.grdMappings().getValue() != null);
			form.getContextMenus().getGenericGridUpdateItem().setVisible(form.grdMappings().getValue() != null);
		}
		form.getContextMenus().getGenericGridAddItem().setVisible(FormMode.VIEW.equals(FormMode.VIEW));
	}
	
	public class stringComparator implements Comparator
	{
		public int compare(Object o1, Object o2)
		{			
			return o1.toString().compareToIgnoreCase(o2.toString());
		}
	}
}
