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

package ims.pathways.forms.targetconfiguration;

import ims.configuration.gen.ConfigFlag;
import ims.core.vo.lookups.PreActiveActiveInactiveStatus;
import ims.domain.exceptions.StaleObjectException;
import ims.domain.exceptions.UniqueKeyViolationException;
import ims.domain.exceptions.UnqViolationUncheckedException;
import ims.framework.Control;
import ims.framework.enumerations.FormMode;
import ims.framework.exceptions.PresentationLogicException;
import ims.pathways.forms.targetconfiguration.GenForm;
import ims.pathways.forms.targetconfiguration.GenForm.grdTargetsRow;
import ims.pathways.vo.TargetConfigurationShortVo;
import ims.pathways.vo.TargetConfigurationShortVoCollection;
import ims.pathways.vo.TargetConfigurationVo;
import ims.pathways.vo.lookups.TargetDateCalculation;

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

	@Override
	protected void onFormOpen(Object[] args) throws ims.framework.exceptions.PresentationLogicException
	{
		open();
		searchForAllActiveRecords();
	}
	
	private void searchForAllActiveRecords() 
	{
		form.cmbSearchStatus().setValue(PreActiveActiveInactiveStatus.ACTIVE);
		TargetConfigurationShortVo filter = new TargetConfigurationShortVo();		
		filter.setStatus(form.cmbSearchStatus().getValue());
		search(filter);
	}

	private void setContextMenu(boolean isRowSelected) 
	{
		if (form.getMode().equals(FormMode.VIEW))
		{
			form.getContextMenus().Pathways.getTargetConfigurationNewItem().setVisible(true);
			form.getContextMenus().Pathways.getTargetConfigurationEditItem().setVisible(isRowSelected);		
		}
		else
		{
			form.getContextMenus().Pathways.hideAllTargetConfigurationMenuItems();
		}
	}
	
	@Override
	protected void onBtnNewClick() throws ims.framework.exceptions.PresentationLogicException
	{
		newInstance();
	}
	@Override
	protected void onBtnEditClick() throws ims.framework.exceptions.PresentationLogicException
	{
		editInstance();
	}
	@Override
	protected void onBtnSaveClick() throws ims.framework.exceptions.PresentationLogicException
	{
		if (save())
			{
				open();
				searchForAllActiveRecords();
			}
	}
	@Override
	protected void onBtnCancelClick() throws ims.framework.exceptions.PresentationLogicException
	{
		form.setMode(FormMode.VIEW);
		open();
		searchForAllActiveRecords();
	}
	public void open() throws ims.framework.exceptions.PresentationLogicException
	{
		form.setMode(FormMode.VIEW);
		clearAll();
		updateControlsState();
	}
	
	private void clearAll() 
	{
		clearSearchCriteria();
		clearTargetsGrid();
		clearContainerDetails();
		form.grdTargets().setFooterValue(null);
		form.grdTargets().setFooterValue("Total records : 0");
	}
	
	private void search(TargetConfigurationShortVo filter) 
	{
		TargetConfigurationShortVoCollection collection  = new TargetConfigurationShortVoCollection();
		collection = domain.listByCriteria(filter);
		
		if (collection == null)
		{
			engine.showMessage("Please provide a valid search criteria!");
			return;
		}
		
		
		if (collection.size() == 0)
		{
			engine.showMessage("No matching records found"); 
			return;
		}
		
		for (int i = 0; i < collection.size(); i++) 
		{
			grdTargetsRow row = form.grdTargets().getRows().newRow();
			row.setColTargetName(collection.get(i).getName());
			row.setColDescr(collection.get(i).getDescription());
			row.setColEventLink(collection.get(i).getEventLinkType());
			row.setColTargetDateCalculation(collection.get(i).getTargetDateCalculation());
			row.setColStatus(collection.get(i).getStatus());
			row.setValue(collection.get(i));	
		}
		form.grdTargets().setFooterValue("Total records : " + collection.size());
	}
	
	public void newInstance() throws ims.framework.exceptions.PresentationLogicException
	{
		clearContainerDetails();
		//clearTargetsGrid();
		form.getLocalContext().setEditedRecord(null);
		form.ctnDetails().customControlMappings().setValue(null);
		form.setMode(FormMode.EDIT);	
		super.bindcmbPathwayStatusLookup();
		form.ctnDetails().cmbTargetDateCalculation().setValue(TargetDateCalculation.PATHWAY_START);
		
		makeContainerCollapsable(false);
		form.ctnDetails().txtPathwayName().setEnabled(true);
		form.ctnDetails().cmbPathwayStatus().removeRow(PreActiveActiveInactiveStatus.INACTIVE);		
	}
	
	private void editInstance() 
	{
		form.setMode(FormMode.EDIT);	
		updateControlsState();
		form.ctnDetails().txtPathwayName().setEnabled(false);
		if (form.getLocalContext().getEditedRecordIsNotNull())
		{
			TargetConfigurationShortVo record = form.getLocalContext().getEditedRecord();
			if (record.getStatus().equals(PreActiveActiveInactiveStatus.ACTIVE))
				{
					form.ctnDetails().cmbPathwayStatus().removeRow(PreActiveActiveInactiveStatus.PREACTIVE);
					form.ctnDetails().cmbPathwayStatus().setValue(record.getStatus());
				}
			else if (record.getStatus().equals(PreActiveActiveInactiveStatus.INACTIVE))
			{
				form.ctnDetails().cmbPathwayStatus().removeRow(PreActiveActiveInactiveStatus.PREACTIVE);
				form.ctnDetails().cmbPathwayStatus().removeRow(PreActiveActiveInactiveStatus.ACTIVE);
				form.ctnDetails().cmbPathwayStatus().setValue(record.getStatus());
			}
			
			// WDEV-18547 
			form.ctnDetails().customControlMappings().setValue(form.getLocalContext().getEditedRecord().getTaxonomyMaps());
		}
		
	}
		
	public boolean save() throws ims.framework.exceptions.PresentationLogicException
	{
		TargetConfigurationVo record = populateDataFromScreen(form.getLocalContext().getEditedRecord());
		
		String[] errors = record.validate();
		if(errors != null && errors.length > 0)
		{
			engine.showErrors(errors);
			
			return false;
		}
		try
		{
			record = domain.save(record);
		}
		catch(StaleObjectException e)
		{
			engine.showMessage(ConfigFlag.UI.STALE_OBJECT_MESSAGE.getValue());
			TargetConfigurationVo updatedRecord = getAndDisplayRecord(record);
			updateRowRecord(updatedRecord);
			
			return false;
		}
		catch(UniqueKeyViolationException e)
		{
			engine.showErrors(new String[]{e.getMessage().toString()});
			return false;
		}
		catch(UnqViolationUncheckedException e)
		{
			engine.showErrors("Taxonomy Map error", new String[]{"TaxonomyMap must be unique!"});
			return false;
		}
		
		form.getLocalContext().setEditedRecord(record);
		
		return true;
		
	}
	
	private TargetConfigurationVo getAndDisplayRecord()
	{
		return getAndDisplayRecord(form.grdTargets().getValue());
	}
	
	private TargetConfigurationVo getAndDisplayRecord(TargetConfigurationShortVo refRecord) 
	{
		clearContainerDetails();
		
		if(refRecord == null)
			return null;
		
		TargetConfigurationVo record = domain.get(refRecord);
		form.getLocalContext().setEditedRecord(record);
		
		populateScreenFromData(record);	
			
		return record;	
	}
	
	private void populateScreenFromData(TargetConfigurationVo record) 
	{
		if(record == null)
			return;
		
		form.ctnDetails().txtPathwayName().setValue(record.getNameIsNotNull() ? record.getName() : null);
		form.ctnDetails().txtPathwayDescr().setValue(record.getDescriptionIsNotNull() ? record.getDescription() : null);
		form.ctnDetails().cmbPathwayEvent().setValue(record.getEventLinkTypeIsNotNull() ? record.getEventLinkType() : null);
		form.ctnDetails().cmbPathwayStatus().setValue(record.getStatusIsNotNull() ? record.getStatus() : null);
		form.ctnDetails().customControlMappings().setValue(record.getTaxonomyMapsIsNotNull() ? record.getTaxonomyMaps() : null);		
		form.ctnDetails().cmbTargetDateCalculation().setValue(record.getTargetDateCalculationIsNotNull()? record.getTargetDateCalculation(): null);
	
	}
	
	private void updateRowRecord(TargetConfigurationVo record) 
	{
		if (record == null)
			return;

		for (int j = 0; j < form.grdTargets().getRows().size(); j++) 
		{
			TargetConfigurationShortVo existingRecord = form.grdTargets().getRows().get(j).getValue();
			if (existingRecord != null && existingRecord.equals(record)) 
			{
				updateRowRecord(form.grdTargets().getRows().get(j), record);
				
				break;
			}
		}
	}
	
	private void updateRowRecord(grdTargetsRow row, TargetConfigurationShortVo record) 
	{
		if (row == null || record == null)
			return;

		row.setColTargetName(record.getName());
		row.setColDescr(record.getDescription());
		row.setColEventLink(record.getEventLinkType());
		row.setColStatus(record.getStatus());
		row.setValue(record);
	}
	
	public void updateControlsState()
	{
		boolean isRowSelected = form.grdTargets().getSelectedRow() != null;
		if (form.getMode().equals(FormMode.VIEW))
		{
			form.btnEdit().setVisible(isRowSelected);
			makeContainerCollapsable(!isRowSelected);
		}
		setContextMenu(isRowSelected);
		form.grdTargets().setFooterValue("Total records : " + form.grdTargets().getRows().size());
	}
	
	private void clearSearchCriteria()
	{
		form.txtSearchName().setValue(null);
		form.cmbSearchEvent().setValue(null);
		form.cmbSearchStatus().setValue(null);
		//WDEV-18090
		form.cmbSearchTargetDateCalFrom().setValue(null);
	}
	
	private void clearContainerDetails() 
	{
		form.ctnDetails().txtPathwayName().setValue(null);
		form.ctnDetails().txtPathwayDescr().setValue(null);
		form.ctnDetails().cmbPathwayEvent().setValue(null);
		form.ctnDetails().cmbPathwayStatus().setValue(null);
		form.ctnDetails().cmbTargetDateCalculation().setValue(null); //WDEV-18080 
		form.ctnDetails().customControlMappings().clear();
		
	}
	
	private void makeContainerCollapsable(boolean isCollapsable)
	{
		form.ctnDetails().setCollapsed(isCollapsable);	
	}
	
	private void clearTargetsGrid() 
	{
		form.grdTargets().getRows().clear();
	}
	
	@Override
	protected void onContextMenuItemClick(int menuItemID, Control sender)
			throws PresentationLogicException 
	{
		switch(menuItemID)
		{
			case GenForm.ContextMenus.PathwaysNamespace.TargetConfiguration.New:
				newInstance();
				break;
			case GenForm.ContextMenus.PathwaysNamespace.TargetConfiguration.Edit:
				editInstance();
				break;
		}	
	}

	@Override
	protected void onFormModeChanged() 
	{
		
		if (form.getMode().equals(FormMode.EDIT))
		{
			form.ctnDetails().customControlMappings().initialize();
			form.ctnDetails().customControlMappings().setComponentMode(FormMode.EDIT);
		}
		else
		{
			form.ctnDetails().customControlMappings().setComponentMode(FormMode.VIEW);
		}
		
		updateControlsState();
	}
	
	protected TargetConfigurationVo populateDataFromScreen(TargetConfigurationVo record)
	{
		if(record == null)
			record = new TargetConfigurationVo();
		
		record.setName(form.ctnDetails().txtPathwayName().getValue());
		record.setDescription(form.ctnDetails().txtPathwayDescr().getValue());
		record.setEventLinkType(form.ctnDetails().cmbPathwayEvent().getValue());
		record.setStatus(form.ctnDetails().cmbPathwayStatus().getValue());
		record.setTaxonomyMaps(form.ctnDetails().customControlMappings().getValue());
		record.setTargetDateCalculation(form.ctnDetails().cmbTargetDateCalculation().getValue());
		return record;
	}

	@Override
	protected void onImbClearClick() throws PresentationLogicException 
	{
		clearAll();
		makeContainerCollapsable(true);
		updateControlsState();
	}

	@Override
	protected void onImbSearchClick() throws PresentationLogicException 
	{
		clearTargetsGrid();
		clearContainerDetails(); 
		updateControlsState();
				
		TargetConfigurationShortVo filter = new TargetConfigurationShortVo();
		
		if (form.txtSearchName().getValue() != null)
		{
			filter.setName(form.txtSearchName().getValue());
		}
		if (form.cmbSearchEvent().getValue() != null)
		{
			filter.setEventLinkType(form.cmbSearchEvent().getValue());
		}
		if (form.cmbSearchStatus().getValue() != null)
		{
			filter.setStatus(form.cmbSearchStatus().getValue());
		}
		
		if (form.cmbSearchTargetDateCalFrom().getValue() != null)
		{
			filter.setTargetDateCalculation(form.cmbSearchTargetDateCalFrom().getValue());
		}
		
		
		search(filter);
		
		form.grdTargets().setFooterValue("Total records : " + form.grdTargets().getRows().size());	
	}
	
	@Override
	protected void onGrdTargetsSelectionChanged()
			throws PresentationLogicException 
	{
		getAndDisplayRecord();
		form.ctnDetails().setCollapsed(false);
		updateControlsState();	
	}
}
