/FileExtraction/Java_unseen/IMS-MAXIMS_openMAXIMS/Source Library/openmaxims_workspace/Nursing/src/ims/nursing/forms/observationforms/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 Callum Wells using IMS Development Environment (version 1.18 build 40702.1400)
// Copyright (C) 1995-2004 IMS MAXIMS plc. All rights reserved.

package ims.nursing.forms.observationforms;


import ims.framework.FormName;
import ims.framework.enumerations.DialogResult;
import ims.framework.enumerations.SortOrder;
import ims.framework.exceptions.FormOpenException;
import ims.framework.exceptions.PresentationLogicException;
import ims.nursing.forms.observationforms.GenForm.groupFilterEnumeration;
import ims.nursing.vo.ObservationForm;
import ims.nursing.vo.ObservationFormCollection;

import java.util.Comparator;
public class Logic extends BaseLogic
{
	private final static int START_DATE_TIME_COLUMN_INDEX = 2;
	private final static int STOP_DATE_TIME_COLUMN_INDEX = 4;
	
	
	protected void onFormOpen() throws FormOpenException
	{
		initialize();
		
		//WDEV-19389 
		if (!(form.getGlobalContext().Core.getCurrentCareContextIsNotNull() && form.getGlobalContext().Nursing.getObservationFormsSearchCriteriaIsNotNull() && form.getGlobalContext().Core.getCurrentCareContext().equals(form.getGlobalContext().Nursing.getObservationFormsSearchCriteria().getCareContext())))
		{
			form.getGlobalContext().Nursing.setObservationFormsSearchCriteria(null);
		}
		
		if(form.getGlobalContext().Nursing.getObservationFormsSearchCriteriaIsNotNull())
		{
			setSearchCriteria(form.getGlobalContext().Nursing.getObservationFormsSearchCriteria());
			try
			{
				onRadioButtongroupFilterValueChanged();
			}
			catch (PresentationLogicException e)
			{
				e.printStackTrace();
			}
		}
		else
			open();	
		//WDEV-19389 - end
	}

	private void setSearchCriteria(ObservationForm observationFormsSearchCriteria)
	{
		form.groupFilter().setValue(Boolean.FALSE.equals(observationFormsSearchCriteria.getIsStopped()) ? groupFilterEnumeration.rdoActive : groupFilterEnumeration.rdoAll);	
	}

	private void initialize() throws FormOpenException
	{
		if (form.getGlobalContext().Core.getCurrentCareContext() == null)
			throw new FormOpenException("Please select a Care Context.");

		form.getGlobalContext().COE.setFormCommenced(null);
		form.getLocalContext().setColStartSortOrder(SortOrder.NONE);
		form.getLocalContext().setColStopSortOrder(SortOrder.NONE);
		
	}

	private void open()
	{
		form.groupFilter().setValue(GenForm.groupFilterEnumeration.rdoActive);

		ObservationFormCollection voCollFormsCommenced;

		ObservationForm voObservationForm = new ObservationForm();
		voObservationForm.setCareContext(form.getGlobalContext().Core.getCurrentCareContext());
		voObservationForm.setIsStopped(Boolean.FALSE);

		voCollFormsCommenced = domain.listFormsCommencement(voObservationForm);
		

		populateGrid(voCollFormsCommenced);
	}

	private void populateGrid(ObservationFormCollection voObserFormColl)
	{
		form.bUpdate().setEnabled(false);

		form.gridForms().getRows().clear();
		form.gridForms().setValue(null);

		if (voObserFormColl != null)
		{
			form.gridForms().getRows().clear();
			
			//for RIE - WDEV-7160 
			form.getLocalContext().setSelectedRecord(null);
			
			// Fill in the grid if there is any data
			GenForm.gridFormsRow row;
			for (int i = 0; i < voObserFormColl.size(); i++)
			{
				row = form.gridForms().getRows().newRow();

				ObservationForm observation = voObserFormColl.get(i);
				
				
				row.setValue(observation);

				row.setColDetails(observation.getDetails());
				row.setTooltipForColDetails(observation.getDetails());

				if (observation.getFormType() != null)
				{
					row.setColFormsCommenced(observation.getFormType().toString());
					row.setTooltipForColFormsCommenced(observation.getFormType().toString());
				}

				if (observation.getHCPStart() != null)
				{
					row.setColStartBy(observation.getHCPStart().getName().toString());
					row.setTooltipForColStartBy(observation.getHCPStart().getName().toString());
				}

				if (observation.getDateTimeStart() != null)
					row.setColStartDate(observation.getDateTimeStart().toString());

				if (observation.getDateTimeStop() != null)
					row.setColStopDate(observation.getDateTimeStop().toString());

				if (observation.getHCPStop() != null)
				{
					row.setColCompleteBy(observation.getHCPStop().getName().toString());
					row.setTooltipForColCompleteBy(observation.getHCPStop().getName().toString());
				}

				if (!observation.getIsStopped().booleanValue())
					row.setColIsActive(form.getImages().Core.AnswerBox_Yes);
				else
					row.setColIsActive(form.getImages().Core.AnswerBox_No);

			}
		}
	}

	protected void onBCompleteClick() throws ims.framework.exceptions.PresentationLogicException
	{
		form.getGlobalContext().COE.setFormCommenced(form.gridForms().getValue());
		engine.open(form.getForms().Nursing.ObservationFormsInput);
	}

	protected void onBNewClick() throws ims.framework.exceptions.PresentationLogicException
	{
		form.getGlobalContext().COE.setFormCommenced(null);
		engine.open(form.getForms().Nursing.ObservationFormsInput);
	}

	protected void onGridFormsSelectionChanged() throws PresentationLogicException
	{
		form.getLocalContext().setSelectedRecord(form.gridForms().getSelectedRow().getValue());
		form.bUpdate().setEnabled(true);
	}

	protected void onRadioButtongroupFilterValueChanged() throws PresentationLogicException
	{
		// List the Observation Forms based on the filter selected
		ObservationFormCollection voFormsCommencedColl;

		ObservationForm voObserForm = new ObservationForm();
		voObserForm.setCareContext(form.getGlobalContext().Core.getCurrentCareContext());
		if (form.groupFilter().getValue().equals(groupFilterEnumeration.rdoActive))
			voObserForm.setIsStopped(Boolean.FALSE);
		else
			voObserForm.setIsStopped(null);

		form.getGlobalContext().Nursing.setObservationFormsSearchCriteria(voObserForm);
		voFormsCommencedColl = domain.listFormsCommencement(voObserForm);
		
		populateGrid(voFormsCommencedColl);
	}

	protected void onFormDialogClosed(FormName formName, DialogResult result) throws PresentationLogicException
	{
		if (formName.equals(form.getForms().Nursing.ObservationFormsInput) && result == DialogResult.OK)
		{
			// Refresh the Grid
			onRadioButtongroupFilterValueChanged();
		}
	}

	@Override
	protected void onGridFormsGridHeaderClicked(int column) throws PresentationLogicException
	{
		switch (column)
		{
			case START_DATE_TIME_COLUMN_INDEX:
				form.getLocalContext().setColStartSortOrder(getNextSortOrder(form.getLocalContext().getColStartSortOrder()));
				doSort(form.getLocalContext().getColStartSortOrder(),"DATETIMESTART");
				return;
			case STOP_DATE_TIME_COLUMN_INDEX:
				form.getLocalContext().setColStopSortOrder(getNextSortOrder(form.getLocalContext().getColStopSortOrder()));
				doSort(form.getLocalContext().getColStopSortOrder(),"DATETIMESTOP");
				return;
			default:
				break;
		}
		
		
	}
	private void doSort(SortOrder sortOrder,String sortByField) throws PresentationLogicException
	{
		ObservationFormCollection values = form.gridForms().getValues();
		values.sort(new CustomFieldObservationFormComparator(sortOrder,sortByField));
		ObservationForm selectionSave = form.gridForms().getValue();
		populateGrid(values);
		form.gridForms().setValue(selectionSave);
		if (selectionSave != null)
		{
			form.gridForms().setValue(selectionSave);
			onGridFormsSelectionChanged();
		}
	}
	private SortOrder getNextSortOrder(SortOrder sort)
	{
		if (sort == null)
			return SortOrder.ASCENDING;
		if (sort.equals(SortOrder.DESCENDING))
			return SortOrder.ASCENDING;
		if (sort.equals(SortOrder.ASCENDING))
			return SortOrder.DESCENDING;
		if (sort.equals(SortOrder.NONE))
			return SortOrder.ASCENDING;
		return SortOrder.ASCENDING;
	}
	private class CustomFieldObservationFormComparator implements Comparator<ObservationForm>
	{
		private int direction = 1;
		private final String fieldName;
		
		public CustomFieldObservationFormComparator(SortOrder sorder,String fieldName)
		{
			this.fieldName = fieldName;
			if (SortOrder.DESCENDING.equals(sorder))
					direction = -1;		
		}
		@SuppressWarnings("unchecked")
		public int compare(ObservationForm o1, ObservationForm o2)
		{
			
			Comparable c1 = (Comparable) o1.getFieldValueByFieldName(fieldName);
			
			Comparable c2 = (Comparable) o2.getFieldValueByFieldName(fieldName);
			if (c1 == null)
				return -1*direction;
			if (c2 == null)
				return direction;
			return c1.compareTo(c2)*direction;
		}
		
	}
}
