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

package ims.nursing.forms.contactview;

import ims.core.vo.ClinicalNotesVo;
import ims.core.vo.ClinicalNotesVoCollection;
import ims.core.vo.HcpCollection;
import ims.core.vo.HcpFilter;
import ims.core.vo.PersonName;
import ims.core.vo.lookups.HcpDisType;
import ims.core.vo.lookups.HcpDisTypeCollection;
import ims.core.vo.lookups.LookupHelper;
import ims.framework.FormName;
import ims.framework.cn.data.TreeNode;
import ims.framework.enumerations.DialogResult;
import ims.framework.enumerations.SortOrder;
import ims.framework.exceptions.PresentationLogicException;
import ims.nursing.vo.ContactFilterVo;

import java.util.Comparator;

public class Logic extends BaseLogic
{
	private final static int DATE_TIME_COL_INDEX=0;
	
	protected void onFormOpen() throws ims.framework.exceptions.FormOpenException
	{
		initialize();
		open();
		
	}

	private void open()
	{
		if (form.cmbDiscipline().getValue() == null && form.qcbHCP().getValue() == null)
			return;
		listContacts();
		
	}

	private void initialize()
	{
		form.chkActiveOnly().setValue(true);
		form.btnNoteCorrection().setEnabled(false);	
		
		//RootNodes are the Discipline instances
		HcpDisTypeCollection coll = LookupHelper.getHcpDisType(domain.getLookupService());
		TreeNode[] rootNodes = coll.getRootNodes();
		for (int i = 0; i < rootNodes.length; i++)
		{
			HcpDisType lk = (HcpDisType)rootNodes[i];
			if (!lk.equals(HcpDisType.NURSING))
				form.cmbDiscipline().newRow(lk,lk.getText());
		}
		//wdev-10791
		if(form.getGlobalContext().Nursing.getContactFilterIsNotNull())
		{
			ContactFilterVo tempVo = form.getGlobalContext().Nursing.getContactFilter();
			form.cmbDiscipline().setValue(tempVo != null ? tempVo.getDiscipline():null);
			if(tempVo.getHcp() != null && tempVo.getHcp().getName() != null)
			{
				form.qcbHCP().newRow(tempVo.getHcp(), tempVo.getHcp().getName().toString());			
				form.qcbHCP().setValue(tempVo.getHcp());
			}
			if(Boolean.TRUE.equals(tempVo.getActive()))
				form.chkActiveOnly().setValue(Boolean.TRUE);
			else
				form.chkActiveOnly().setValue(Boolean.FALSE);
		}
		//---------
		
		form.qcbHCP().setEnabled(form.cmbDiscipline().getValue()!=null);
		form.btnOk().setEnabled(form.cmbDiscipline().getValue()!=null);
		form.getLocalContext().setselectedRecord(null);			//wdev-10799
		
	}
	
	protected void onBtnNewClick() throws ims.framework.exceptions.PresentationLogicException
	{
		// Set clinical notes to null so the form will know it's for a new note
		form.getGlobalContext().COE.setClinicalNotesVo(null);
		form.getGlobalContext().COE.setContactCorrection(Boolean.FALSE);
		engine.open(form.getForms().Nursing.ContactInput);
	}
	
	protected void onBtnNoteCorrectionClick() throws PresentationLogicException 
	{
		form.getGlobalContext().COE.setClinicalNotesVo(form.grdContacts().getValue());
		form.getGlobalContext().COE.setContactCorrection(Boolean.TRUE);
		engine.open(form.getForms().Nursing.ContactInput);
	}
	
	protected void onCmbDisciplineValueChanged() throws PresentationLogicException 
	{
			
		form.grdContacts().getRows().clear();			
		form.qcbHCP().clear();
		form.btnOk().setEnabled(form.cmbDiscipline().getValue() != null);
		form.qcbHCP().setEnabled(form.cmbDiscipline().getValue() != null);
		form.btnNoteCorrection().setEnabled(false);			//wdev-10797
		
		
	}
	
	protected void onBtnOkClick() throws ims.framework.exceptions.PresentationLogicException 
	{
		listContacts();
	}
	
	private void listContacts()
	{
		form.getLocalContext().setDateTimeSortOrder(SortOrder.NONE);
		
		if (form.cmbDiscipline().getValue() == null) 
		{
			engine.showErrors(new String[]{"Discipline is mandatory"});
			
			return;
		}
//		ims.core.vo.ClinicalEpisode voClinicalEpisode = form.getGlobalContext().Core.getClinicalEpisode();
		ClinicalNotesVoCollection voListContacts = domain.listContacts(form.qcbHCP().getValue(), form.cmbDiscipline().getValue(), form.getGlobalContext().Core.getCurrentCareContext(),form.chkActiveOnly().getValue());
		
		form.grdContacts().getRows().clear();
		form.getLocalContext().setselectedRecord(null);			//wdev-10799
		if (voListContacts == null || voListContacts.size() == 0 )
		{
			engine.showMessage("No Contact records were found for your search criteria.");
			form.getGlobalContext().Nursing.setContactFilter(null);		//wdev-10791
			return;
		}
		populateGridFromData(voListContacts);
		form.grdContacts().setValue(null);
		form.btnNoteCorrection().setEnabled(false);
		RefreshFilterSearchCriteria();//wdev-10791
	}
	//wdev-10791
	private void RefreshFilterSearchCriteria()
	{
		ContactFilterVo tempVo = new ContactFilterVo();
		tempVo.setDiscipline(form.cmbDiscipline().getValue());
		tempVo.setHcp(form.qcbHCP().getValue());
		tempVo.setActive(form.chkActiveOnly().getValue());
		form.getGlobalContext().Nursing.setContactFilter(tempVo);
		
		
		
		
	}
	//---------
	private void populateGridFromData(ClinicalNotesVoCollection voListContacts)
	{
		GenForm.grdContactsRow row;			
		ClinicalNotesVo voContactRecord;
		
		for (int i=0; i< voListContacts.size(); i++)
		{
			voContactRecord = voListContacts.get(i);			
			row = form.grdContacts().getRows().newRow();
			
			row.setcolDate(voContactRecord.getRecordingDateTime().toString());
			if (voContactRecord.getAuthoringInfoIsNotNull())
			{
				if (voContactRecord.getAuthoringInfo().getAuthoringHcpIsNotNull())
					row.setcolBy(voContactRecord.getAuthoringInfo().getAuthoringHcp().getName().toString());
			}
			if (voContactRecord.getDiscipline() != null)
				row.setColDiscipline(voContactRecord.getDiscipline().getText());

			if (voContactRecord.getIsCorrectedIsNotNull())
			{
				if (voContactRecord.getIsCorrected().booleanValue() == true)  // Correction has been added
					row.setcolNote(voContactRecord.getClinicalNote() + "\nCorrected By: " + voContactRecord.getCurrentStatus().getCorrectedBy() + " on " + voContactRecord.getCurrentStatus().getDateTime().getDate() + " at " + voContactRecord.getCurrentStatus().getDateTime().getTime() + " for the following reason:\n" + voContactRecord.getCurrentStatus().getCorrectionReason());
				else
					row.setcolNote(voContactRecord.getClinicalNote());
			}
			
			if (voContactRecord.getIsCorrectedIsNotNull())
			{
				if (voContactRecord.getIsCorrected().booleanValue())
					row.setcolIsActive(form.getImages().Core.AnswerBox_No);
				else
					row.setcolIsActive(form.getImages().Core.AnswerBox_Yes);
			}
			
			row.setValue(voContactRecord);
		}
	}

	protected void onGrdContactsSelectionChanged() throws PresentationLogicException 
	{
		if(form.grdContacts().getSelectedRow().getValue()!= null)
		{
			form.getLocalContext().setselectedRecord(form.grdContacts().getSelectedRow().getValue());
			
		}
		
		form.btnNoteCorrection().setEnabled(true);
	}
	
	protected void onFormDialogClosed(FormName formName, DialogResult result) throws PresentationLogicException 
	{
		if (formName.equals(form.getForms().Nursing.ContactInput))
		{
			listContacts();
		}		
	}

	protected void onCmbHCPTextSubmited(String value) throws PresentationLogicException 
	{
		if (form.cmbDiscipline().getValue() != null)
		{	
			HcpFilter voFilter = new HcpFilter();
			PersonName voPname = new PersonName();
			
			voPname.setSurname(value);
			voFilter.setQueryName(voPname);

			HcpDisType voHCPDisciplineInstance = form.cmbDiscipline().getValue();
			voFilter.setHcpType(voHCPDisciplineInstance);
			
			HcpCollection hcpColl = domain.listHcps(voFilter);
			
			if (hcpColl != null)
			{
				form.qcbHCP().clear();
				for (int i = 0; i < hcpColl.size(); i++)
				{
					form.qcbHCP().newRow(hcpColl.get(i), hcpColl.get(i).getName().toString());					
				}
				if (hcpColl.size() == 1)
					form.qcbHCP().setValue(hcpColl.get(0));
				else if (hcpColl.size() > 1)
					form.qcbHCP().showOpened();
				
				form.btnOk().setEnabled(true);
			}
		}
	}

	@Override
	protected void onGrdContactsGridHeaderClicked(int column) throws PresentationLogicException
	{
		if (DATE_TIME_COL_INDEX == column)
		{
			ClinicalNotesVo selectedValue = form.grdContacts().getValue();
			ClinicalNotesVoCollection data = new ClinicalNotesVoCollection();
			
			for (int i = 0 ; i < form.grdContacts().getRows().size() ; i ++)
			{
				data.add(form.grdContacts().getRows().get(i).getValue());
			}
			form.getLocalContext().setDateTimeSortOrder(getNextOrder(form.getLocalContext().getDateTimeSortOrder()));
			data.sort(new DateTimeClinicalNotesComparator(form.getLocalContext().getDateTimeSortOrder()));
			form.grdContacts().getRows().clear();			
			populateGridFromData(data);
			form.grdContacts().setValue(selectedValue);
			if (form.grdContacts().getValue()!= null)
				onGrdContactsSelectionChanged();
			
		}
		
	}		
	private SortOrder getNextOrder(SortOrder order)
	{
		if (SortOrder.ASCENDING.equals(order))
			return SortOrder.DESCENDING;
		return SortOrder.ASCENDING;
	}
	
	class DateTimeClinicalNotesComparator implements Comparator<ClinicalNotesVo>
	{
		private int direction = 1;
		public DateTimeClinicalNotesComparator(SortOrder order)
		{
			if (SortOrder.DESCENDING.equals(order))
			{
				direction = -1;;
			}
		}
		public int compare(ClinicalNotesVo o1, ClinicalNotesVo o2)
		{
			if (!o1.getRecordingDateTimeIsNotNull())
				return direction*-1;
			if (!o2.getRecordingDateTimeIsNotNull())
				return direction;
			return direction*o1.getRecordingDateTime().compareTo(o2.getRecordingDateTime());
		}
	}
}
