/FileExtraction/Java_unseen/IMS-MAXIMS_openMAXIMS/Source Library/openmaxims_workspace/Pathways/src/ims/pathways/forms/adminevent/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 Bogdan Tofei using IMS Development Environment (version 1.80 build 5007.25751)
// Copyright (C) 1995-2013 IMS MAXIMS. All rights reserved.

package ims.pathways.forms.adminevent;

import ims.core.vo.MemberOfStaffLiteVo;
import ims.core.vo.RecordingUserInformationVo;
import ims.core.vo.enums.MosType;
import ims.domain.exceptions.DomainInterfaceException;
import ims.domain.exceptions.StaleObjectException;
import ims.framework.FormName;
import ims.framework.MessageButtons;
import ims.framework.MessageIcon;
import ims.framework.enumerations.DialogResult;
import ims.framework.enumerations.FormMode;
import ims.framework.exceptions.PresentationLogicException;
import ims.framework.utils.Date;
import ims.framework.utils.DateTime;
import ims.pathways.forms.adminevent.GenForm.grdAdminEventsRow;
import ims.pathways.vo.AdminEventVo;
import ims.pathways.vo.AdminEventVoCollection;
import ims.pathways.vo.RTTStatusEventMapVo;
import ims.pathways.vo.RTTStatusEventMapVoCollection;
import ims.pathways.vo.lookups.AdminEventOutcome;
import ims.pathways.vo.lookups.AdminEventOutcomeCollection;
import ims.pathways.vo.lookups.LookupHelper;
import ims.vo.interfaces.IMos;

import java.util.ArrayList;

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

	@Override
	protected void onFormOpen(Object[] args) throws ims.framework.exceptions.PresentationLogicException
	{
		if (args != null && args.length > 0 && args[0] != null && args[0] instanceof FormMode)
		{
			open((FormMode) args[0]);
		}
		if (args != null && args.length > 1 && args[1] != null && args[1] instanceof DateTime)
		{
			form.getLocalContext().setNotBeforeDateTime((DateTime)args[1]);
		}
		
		//WDEV-22517
		form.getLocalContext().setRttStatusEventMapCollConfigured(domain.getAdminEventOutcomeCollConfigured()); 
		populateOutcomeCombo();
		
//		else
//			return;
	}

	private void initialise()
	{
		form.ccRecordingUser().initialize(MosType.ALL);
		form.ccRecordingUser().setValue((IMos) domain.getMosUser());
		form.ccRecordingUser().isRequired(true);
		form.dtimRecording().setValue(new DateTime());
	}
	
	//WDEV-22517
	private void populateOutcomeCombo()
	{
		form.cmbOutcome().clear();
		
		AdminEventOutcomeCollection lookupCollection = LookupHelper.getAdminEventOutcome(domain.getLookupService());
		
		for(int i = 0; i < lookupCollection.size(); i++)
		{
			if (isOutcomeConfigured(lookupCollection.get(i), form.getLocalContext().getRttStatusEventMapCollConfigured()))
			{
				form.cmbOutcome().newRow(lookupCollection.get(i), lookupCollection.get(i).getText(), lookupCollection.get(i).getImage(), lookupCollection.get(i).getTextColor());
			}
		}
	}

	//WDEV-22517
	private boolean isOutcomeConfigured(AdminEventOutcome adminEventOutcome, RTTStatusEventMapVoCollection rttStatusEventMapVoCollection)
	{
		if (adminEventOutcome==null || rttStatusEventMapVoCollection==null || rttStatusEventMapVoCollection.size()==0)
			return false;
		
		for (RTTStatusEventMapVo rttStatusEventMap : rttStatusEventMapVoCollection)
		{
			if (rttStatusEventMap!=null && rttStatusEventMap.getEncounterInstance()!=null && adminEventOutcome.getID() ==rttStatusEventMap.getEncounterInstance().getID())
			{
				return true;
			}
		}
		
		return false;
	}

	private void open(FormMode formMode)
	{
		clearAdminEventDetails();
		//WDEV-18487
		form.getLocalContext().setCanAddEvent(Boolean.TRUE);
		if (FormMode.EDIT.equals(formMode))
			initialise();
		//WDEV-18487		
		if (FormMode.VIEW.equals(formMode) && form.getForms().RefMan.PatientReferralStatusList.equals(engine.getPreviosFormName()))
		{
			form.getLocalContext().setCanAddEvent(Boolean.FALSE);
		}

		populateAdminEventsGrid();
		form.setMode(formMode);
	}

	private void populateAdminEventsGrid()
	{
		form.grdAdminEvents().getRows().clear();

		AdminEventVoCollection adminEvents = domain.getAdminEvents(form.getGlobalContext().RefMan.getCatsReferral());

		if (adminEvents == null)
			return;

		for (int i = 0; i < adminEvents.size(); i++)
		{
			AdminEventVo adminEvent = adminEvents.get(i);

			if (adminEvent == null)
				continue;

			grdAdminEventsRow newRow = form.grdAdminEvents().getRows().newRow();

			if (adminEvent.getRecordingDetails() != null)
			{
				newRow.setColRecordingUser(adminEvent.getRecordingDetails().getRecordingUser() != null ? adminEvent.getRecordingDetails().getRecordingUser().toString() : "");
				newRow.setTooltipForColRecordingUser(adminEvent.getRecordingDetails().getRecordingUser() != null ? adminEvent.getRecordingDetails().getRecordingUser().toString() : "");
				newRow.setColDateTime(adminEvent.getRecordingDetails().getRecordingDateTime() != null ? adminEvent.getRecordingDetails().getRecordingDateTime().toString() : "");
			}

			newRow.setColOutcome(adminEvent.getOutcome().getText());
			newRow.setTooltipForColOutcome(adminEvent.getOutcome().getText());
			newRow.setColEventMethod(adminEvent.getEventMethod().getText());
			newRow.setTooltipForColEventMethod(adminEvent.getEventMethod().getText());
			newRow.setColEventDetails(adminEvent.getEventDetails());
			
			newRow.setColOutcomeReason(adminEvent.getOutcomeReason() != null ? adminEvent.getOutcomeReason().getText() : ""); //WDEV-20059
			newRow.setTooltipForColOutcomeReason(adminEvent.getOutcomeReason() != null ? adminEvent.getOutcomeReason().getText() : ""); //WDEV-20059
			
			newRow.setValue(adminEvents.get(i));
		}
	}

	@Override
	protected void onBtnCancelClick() throws ims.framework.exceptions.PresentationLogicException
	{
		open(FormMode.VIEW);
	}

	@Override
	protected void onBtnSaveClick() throws ims.framework.exceptions.PresentationLogicException
	{
		saveThenReopen(null);
	}

	// WDEV-20636
	private void saveThenReopen(Date ecadDate)
	{
		if (save(ecadDate))
		{
			open(FormMode.VIEW);
			form.grdAdminEvents().setValue(form.getLocalContext().getAdminEvent());
			populateScreenFromData();
		}
		
	}
	
	protected void onFormDialogClosed(FormName formName, DialogResult result) throws PresentationLogicException
	{		
		//refresh the appt tab after possible placing of order
		if(formName.equals(form.getForms().Core.DateEntryDialog) && result.equals(DialogResult.OK))
		{
			 saveThenReopen(form.getGlobalContext().Core.getGenericDate());
		}
	}

	private boolean save(Date ecadDate)
	{
		int repeats = 0;

		do
		{
			try
			{
				AdminEventVo adminEvent = populateDataFromScreen();

				adminEvent.setEcadDate(ecadDate); // WDEV-20636 For Decision to Treat and Cancer Referrals, ecad date may have been supplied via DateEntryDialog

				String[] errors = adminEvent.validate(validateUiRules());

				if (errors != null && errors.length > 0)
				{
					engine.showErrors(errors);
					return false;
				}
				// WDEV-20636 //WDEV-22702  moved this here to avoid screen hanging
				// If Decision to Treat was chosen, and this is a cancer pathway we need to ask for the Earliest Clinically Appropriate Date
				if (ecadDate == null 
						&& (AdminEventOutcome.DECISION_TO_TREAT.equals(form.cmbOutcome().getValue()) || AdminEventOutcome.DECISION_TO_TREAT_ACTIVE_MONITORING.equals(form.cmbOutcome().getValue()))
						&& domain.isCancerReferral(form.getGlobalContext().RefMan.getCatsReferral()))
				{
					engine.open(form.getForms().Core.DateEntryDialog, "ECAD Date");
					return false;
				}

				form.getLocalContext().setAdminEvent(domain.saveAdminEvent(adminEvent, form.getGlobalContext().RefMan.getCatsReferral()));

				if (form.getLocalContext().getAdminEvent() == null)
				{
					engine.showMessage("Save is only possible if RTT_STATUS_POINT_FUNCTIONALITY flag is TRUE", "Warning", MessageButtons.OK, MessageIcon.WARNING);
					open(FormMode.VIEW);
					return false;
				}

				//WDEV-18468
				if (AdminEventOutcome.ACTIVE_MONITORING_INITIATED_BY_PATIENT.equals(adminEvent.getOutcome()) || AdminEventOutcome.ACTIVE_MONITORING_INITIATED_BY_CARE_PROFESSIONAL.equals(adminEvent.getOutcome())) 
				{
					if (domain.areFutureTCIsForReferral(form.getGlobalContext().RefMan.getCatsReferral()))
					{
						engine.showMessage("This patient has future TCIs which may be impacted as a result of Active Monitoring.", "Warning", MessageButtons.OK, MessageIcon.WARNING);
					}
				}
				
				open(FormMode.VIEW);
				return true;
			}
			catch (StaleObjectException e)
			{
				engine.showMessage(ims.configuration.gen.ConfigFlag.UI.STALE_OBJECT_MESSAGE.getValue());
				open(FormMode.VIEW);
				return false;
			}
			catch (DomainInterfaceException e)
			{
				repeats++;
				e.printStackTrace();
			}
		}
		while (repeats < 3);

		engine.showMessage("An Error occured during the process. Please try again or start the process again.");
		return false;
	}

	private String[] validateUiRules()
	{
		ArrayList<String> listOfErrors = new ArrayList<String>();

		if (form.ccRecordingUser().getValue() == null)
		{
			listOfErrors.add("Recording User is mandatory");
		}

		if (form.dtimRecording().getValue() == null)
		{
			listOfErrors.add("Event Date/Time is mandatory");
		}
		if(form.getLocalContext().getNotBeforeDateTimeIsNotNull()&&form.getLocalContext().getNotBeforeDateTime().isGreaterOrEqualThan(form.dtimRecording().getValue()))
		{
			listOfErrors.add("Event Date/Time must be later than the date of most recent RTT Status");
		}

		int errorCount = listOfErrors.size();
		String[] result = new String[errorCount];

		for (int x = 0; x < errorCount; x++)
			result[x] = (String) listOfErrors.get(x);

		return result;
	}

	private AdminEventVo populateDataFromScreen()
	{
		AdminEventVo adminEvent = new AdminEventVo();

		RecordingUserInformationVo recordingInformation = new RecordingUserInformationVo();

		recordingInformation.setRecordingUser((MemberOfStaffLiteVo) form.ccRecordingUser().getValue());
		recordingInformation.setRecordingDateTime(form.dtimRecording().getValue());
		
		adminEvent.setRecordingDetails(recordingInformation);
		adminEvent.setOutcomeReason(form.cmbOutcomeReason().getValue()); //WDEV-20059
		adminEvent.setOutcome(form.cmbOutcome().getValue());
		adminEvent.setEventMethod(form.cmbEventMethod().getValue());
		adminEvent.setEventDetails(form.txtEventDetails().getValue());
		adminEvent.setAdmittedStop(form.chkAdmittedStop().getValue());

		return adminEvent;
	}

	@Override
	protected void onBtnNewClick() throws ims.framework.exceptions.PresentationLogicException
	{
		form.getLocalContext().setAdminEvent(null);
		form.getGlobalContext().Core.setGenericDate(null); //WDEV-22702
		form.grdAdminEvents().setValue(null);
		clearAdminEventDetails();
		initialise();
		form.setMode(FormMode.EDIT);
	}

	private void clearAdminEventDetails()
	{
		form.ccRecordingUser().setValue(null);
		form.dtimRecording().setValue(null);
		form.cmbOutcomeReason().setValue(null); //WDEV-20059
		form.cmbEventMethod().setValue(null);
		form.cmbOutcome().setValue(null);
		form.txtEventDetails().setValue(null);
		form.chkAdmittedStop().setValue(null);
	}

	@Override
	protected void onGrdAdminEventsSelectionChanged()
	{
		populateScreenFromData();
	}

	private void populateScreenFromData()
	{
		clearAdminEventDetails();

		AdminEventVo adminEvent = form.grdAdminEvents().getValue();

		if (adminEvent == null)
			return;

		if (adminEvent.getRecordingDetails() != null)
		{
			form.ccRecordingUser().setValue(adminEvent.getRecordingDetails().getRecordingUser());
			form.dtimRecording().setValue(adminEvent.getRecordingDetails().getRecordingDateTime());
		}

		form.cmbOutcomeReason().setValue(adminEvent.getOutcomeReason()); //WDEV-20059
		form.cmbOutcome().setValue(adminEvent.getOutcome());
		form.cmbEventMethod().setValue(adminEvent.getEventMethod());
		form.txtEventDetails().setValue(adminEvent.getEventDetails());
		form.chkAdmittedStop().setValue(adminEvent.getAdmittedStop());
	}

	@Override
	protected void onBtnCloseClick() throws PresentationLogicException
	{
		engine.close(DialogResult.CANCEL);
	}
	//WDEV-18487
	@Override
	protected void onFormModeChanged()
	{
		updateControlsState();
	}

	private void updateControlsState()
	{
		form.btnNew().setVisible(FormMode.VIEW.equals(form.getMode()) && form.getLocalContext().getCanAddEvent());
	}
}	//------------WDEV-18487 ends here
