/FileExtraction/Java_unseen/IMS-MAXIMS_openMAXIMS/Source Library/openmaxims_workspace/Nursing/src/ims/nursing/forms/clinicaladmission/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 Cornel Ventuneac using IMS Development Environment (version 1.71 build 3763.19232)
// Copyright (C) 1995-2010 IMS MAXIMS. All rights reserved.

package ims.nursing.forms.clinicaladmission;

import ims.configuration.AppRight;
import ims.configuration.gen.ConfigFlag;
import ims.core.vo.AdmissionDetailVo;
import ims.core.vo.AuthoringInformationVo;
import ims.core.vo.CareContextShortVo;
import ims.core.vo.Hcp;
import ims.core.vo.HcpLiteVo;
import ims.core.vo.MemberOfStaffLiteVo;
import ims.core.vo.NurseVo;
import ims.core.vo.enums.MosType;
import ims.core.vo.lookups.HcpDisType;
import ims.domain.exceptions.DomainInterfaceException;
import ims.domain.exceptions.StaleObjectException;
import ims.domain.exceptions.UniqueKeyViolationException;
import ims.framework.enumerations.FormMode;
import ims.framework.exceptions.CodingRuntimeException;
import ims.framework.exceptions.PresentationLogicException;
import ims.framework.utils.DateTime;
import ims.nursing.forms.clinicaladmission.GenForm.grdActionRow;
import ims.nursing.vo.AdmissionChecklistVo;
import ims.nursing.vo.AdmissionChecklistVoCollection;
import ims.nursing.vo.AdmissionDetailForClinicalAdmissionVo;
import ims.nursing.vo.CarePlanCollection;
import ims.nursing.vo.ClinicalAdmissionListVo;
import ims.nursing.vo.ClinicalAdmissionListVoCollection;
import ims.nursing.vo.ClinicalAdmissionVo;
import ims.nursing.vo.PasEventForClinicalAdmissionVo;
import ims.nursing.vo.lookups.AdmissionQuestion;
import ims.nursing.vo.lookups.AdmissionQuestionCollection;
import ims.nursing.vo.lookups.CarePlanStatus;
import ims.vo.interfaces.IMos;

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

	protected void onFormOpen(Object[] args) throws ims.framework.exceptions.PresentationLogicException
	{
		initialize();
		open();
	}
	
	protected void onFormModeChanged()
	{
			
	}
	
	private void initialize()
	{
		form.ccAdmittingNurse().initialize(MosType.HCP,HcpDisType.NURSING);
		form.ccConfirmedBy().initialize(MosType.ALL);
		form.ccDischarged().initialize(MosType.ALL);
		
		//form.getLocalContext().setisOpenCarePlan(false);
		CarePlanCollection carePlColl = domain.getCareplans(form.getGlobalContext().Core.getCurrentCareContext());
		form.getLocalContext().setisOpenCarePlan(iterateCarePlanCollection(carePlColl));
		
		//WDEV-13846 
		form.getLocalContext().setclinicalAdmission(null);
		form.getLocalContext().setlocalContextForRie(null);
	}
	protected void onBtnCancelClick() throws ims.framework.exceptions.PresentationLogicException
	{
		form.setMode(FormMode.VIEW);
		open();
	}
	
	protected void onBtnSaveClick() throws ims.framework.exceptions.PresentationLogicException
	{
		if(save())
			open();
	}
	
	protected void onBtnUndischargeClick() throws ims.framework.exceptions.PresentationLogicException
	{
		form.setMode(FormMode.EDIT);
		form.btnSave().setText("Ok");
		form.ccDischarged().setValue(null);
		form.dtimDischarged().setValue(null);
		form.getLocalContext().setbuttonAction(6);
		updateControlsState();
		
	}
	
	protected void onBtnDischargeClick() throws ims.framework.exceptions.PresentationLogicException
	{
		if(form.getLocalContext().getisOpenCarePlan() == true)
		{
			engine.showMessage("Please complete Care Plans prior to discharging patient.");
			return;
		}
		form.setMode(FormMode.EDIT);
		form.getLocalContext().setbuttonAction(5);
		updateControlsState();
		form.ccDischarged().setValue((IMos)domain.getMosUser());
		form.dtimDischarged().setValue(new DateTime());
	}
	
	protected void onBtnConfirmClick() throws ims.framework.exceptions.PresentationLogicException
	{
		form.setMode(FormMode.EDIT);
		form.getLocalContext().setbuttonAction(4);
		updateControlsState();
		form.ccConfirmedBy().setValue((IMos)domain.getMosUser());
		form.dtimConfirmed().setValue(new DateTime());
	}
	
	protected void onBtnCopyClick() throws ims.framework.exceptions.PresentationLogicException
	{
		if(form.getLocalContext().getpreviousClinicalAdmission() == null)
			throw new CodingRuntimeException("Copy Last option cannot be available when no previous Clinical Admission is recorded for selected patient.");
		
		if(!isCurrentCCLinkedToPASEvent())
		{
			engine.showMessage("Patient is not currently an inpatient."); //WDEV-18762
		}
		
		form.setMode(FormMode.EDIT);
		
		clearInstanceControls();
		populateGridAction(null);
		form.txtClientsUnderstanding().setValue(form.getLocalContext().getpreviousClinicalAdmission().getClientUnderstanding());
		form.txtSocialCircumstance().setValue(form.getLocalContext().getpreviousClinicalAdmission().getSocialCircumstance());
		form.getLocalContext().setbuttonAction(3);
		
		populatePASEventDetails(getPASDetails()); //	WDEV-10976
		
		updateControlsState();
	}
	
	protected void onBtnEditClick() throws ims.framework.exceptions.PresentationLogicException
	{
		form.setMode(FormMode.EDIT);
		form.getLocalContext().setbuttonAction(2);
		updateControlsState();
	}
	
	protected void onBtnNewClick() throws ims.framework.exceptions.PresentationLogicException
	{
		if(!isCurrentCCLinkedToPASEvent())
		{
			engine.showMessage("Patient is not a current inpatient");
		}
		
		form.setMode(FormMode.EDIT);
		form.getLocalContext().setbuttonAction(1);
		clearInstanceControls();
		populateGridAction(null);
		form.getLocalContext().setclinicalAdmission(null);	
		form.getLocalContext().setlocalContextForRie(null);//WDEV-13846 
		
		populatePASEventDetails(getPASDetails()); //	WDEV-10976
		
		updateControlsState();
		//wdev-11945
		if(domain.getHcpUser() instanceof Hcp)
		{
			Hcp temp = (Hcp)domain.getHcpUser();
			if(temp != null)
			{
				HcpDisType hcptype =getParentNodeHcp(temp.getHcpType()); 
				if( hcptype != null && hcptype.equals(HcpDisType.NURSING))
					form.ccAdmittingNurse().setValue((NurseVo)domain.getNurse(temp));
			}
		}
		//------
		
	}

	//	WDEV-10976
	private Object getPASDetails() 
	{
		if(form.getGlobalContext().Core.getCurrentCareContext().getPasEvent() == null)
			return null;
		
		AdmissionDetailForClinicalAdmissionVo admission = domain.getPASAdmissionDetails(form.getGlobalContext().Core.getCurrentCareContext().getPasEvent());
		
		if(admission != null)
			return admission;
		
		PasEventForClinicalAdmissionVo pasEvent = domain.getPASEvent(form.getGlobalContext().Core.getCurrentCareContext().getPasEvent());
		
		return pasEvent;
	}
	
	//	WDEV-10976
	private void populatePASEventDetails(Object pasAdmissionDetails) 
	{
		if(pasAdmissionDetails instanceof AdmissionDetailForClinicalAdmissionVo)
		{
			AdmissionDetailForClinicalAdmissionVo admission = (AdmissionDetailForClinicalAdmissionVo) pasAdmissionDetails;
			
			populatePASEvent(admission.getPasEvent());
			form.txtSource().setValue(admission.getSourceOfAdmissionIsNotNull() ? admission.getSourceOfAdmission().getIItemText() : null);
		}
		else if (pasAdmissionDetails instanceof PasEventForClinicalAdmissionVo)
		{
			populatePASEvent((PasEventForClinicalAdmissionVo) pasAdmissionDetails);
		}
	}

	//	WDEV-10976
	private void populatePASEvent(PasEventForClinicalAdmissionVo pasAdmissionDetails) 
	{
		if(pasAdmissionDetails == null)
			return;
		
		form.txtDateTime().setValue(pasAdmissionDetails.getEventDateTime() != null ? pasAdmissionDetails.getEventDateTime().toString() : null);
		form.txtConsultant().setValue(pasAdmissionDetails.getConsultantIsNotNull() ? pasAdmissionDetails.getConsultant().getIMosName() : null);
		form.txtWard().setValue(pasAdmissionDetails.getLocationIsNotNull() ? pasAdmissionDetails.getLocation().getName() : null);
	}

	private HcpDisType getParentNodeHcp(HcpDisType hcpvo)
	{
		if(hcpvo == null)
			return null;
		if(hcpvo.getParent() == null)
			return hcpvo;
		else
			return getParentNodeHcp(hcpvo.getParent());
		
	}
	
	private boolean isCurrentCCLinkedToPASEvent() 
	{
		if(form.getGlobalContext().Core.getCurrentCareContextIsNotNull()
				&& form.getGlobalContext().Core.getCurrentCareContext().getPasEvent() == null)
		{
			return false;
		}
	
		return true;
	}

	private void open()
	{
		//populate record browser
		populateRecordBrowser(domain.listClinicalAdmissions(form.getGlobalContext().Core.getPatientShort()));
		checkForPreviousAdmission();
		updateControlsState();
	}
	
	private void checkForPreviousAdmission() 
	{
		ClinicalAdmissionVo clinAdmPreviousVo = domain.getPreviousClinicalAdmission(form.getGlobalContext().Core.getPatientShort().getID_Patient());
		form.getLocalContext().setpreviousClinicalAdmission(clinAdmPreviousVo);
	}

	private void openClinicalAdmission(ClinicalAdmissionVo voCA) 
	{
		//ClinicalAdmissionVo clinAdmVo = null;
		
		//wdev-13846
		if (voCA==null)
			return;
		
		CareContextShortVo voCCShort = domain.getCareContextShort(voCA.getCareContext());
		/*if (voCA == null)
		{
			clinAdmVo = domain.getClinicalAdmission(form.getGlobalContext().Core.getCurrentCareContext());
			voCCShort = form.getGlobalContext().Core.getCurrentCareContext();
			ClinicalAdmissionVo clinAdmPreviousVo = domain.getPreviousClinicalAdmission(form.getGlobalContext().Core.getPatientShort().getID_Patient());
			form.getLocalContext().setpreviousClinicalAdmission(clinAdmPreviousVo);

			CarePlanCollection carePlColl = domain.getCareplans(voCCShort);
			form.getLocalContext().setisOpenCarePlan(iterateCarePlanCollection(carePlColl));
			form.getLocalContext().setAllowEditing(false);
		}
		else
		{
			clinAdmVo = voCA;
			voCCShort = domain.getCareContextShort(voCA.getCareContext());
			form.getLocalContext().setpreviousClinicalAdmission(null);
			form.getLocalContext().setAllowEditing(true);
		}*/
		
		//form.getLocalContext().setAllowEditing(true);
		//form.recbrAdmissions().setValue((ClinicalAdmissionListVo)clinAdmVo);
		
		AdmissionDetailVo admdetVo = null;
		if(voCCShort.getPasEvent() != null)
		   admdetVo = domain.getAdmissionDetail(voCCShort.getPasEvent().getID_PASEvent());
		
		//form.getLocalContext().setclinicalAdmission(clinAdmVo);
		form.getLocalContext().setadmissionDetail(admdetVo);

		populateScreenFromData(voCA, admdetVo, voCCShort);
		
		form.setMode(FormMode.VIEW);
	}

	private void populateRecordBrowser(ClinicalAdmissionListVoCollection collClinicalAdmissions)
	{
		//form.getLocalContext().setAllowRecording(true);
		if(collClinicalAdmissions == null)
			return;
		
		Boolean bFound = false;
		ClinicalAdmissionListVo voToOpen = null;
		form.recbrAdmissions().clear();
		
		
		for (int i = 0; i < collClinicalAdmissions.size(); i++)
		{
			ClinicalAdmissionListVo vo = collClinicalAdmissions.get(i);			
			form.recbrAdmissions().newRow(collClinicalAdmissions.get(i), getDisplayString(vo));
			
			if (collClinicalAdmissions.get(i).getCareContextIsNotNull() 
				&& form.getGlobalContext().Core.getCurrentCareContextIsNotNull()
				&& collClinicalAdmissions.get(i).getCareContext().equals(form.getGlobalContext().Core.getCurrentCareContext()))
			{
				bFound = true;
				voToOpen = collClinicalAdmissions.get(i);
				
				//local context is set only if clinical admission selected in the record browser is linked to the current care context 
				form.getLocalContext().setclinicalAdmission(domain.getClinicalAdmission(voToOpen.getCareContext()));
				//WDEV-13846
				form.getLocalContext().setlocalContextForRie(form.getLocalContext().getclinicalAdmission());
			}
		}
		
		if (bFound)
		{
			form.recbrAdmissions().setValue(voToOpen);
		}
		else
		{
			//form.recbrAdmissions().newRow(null, "");
			form.recbrAdmissions().newRow(0, null, "");
		}
		
		recordBrowserValueChanged();
	}

	private String getDisplayString(ClinicalAdmissionListVo voCA)
	{
		StringBuffer sb = new StringBuffer();
		if(voCA != null)
		{
			sb.append("Admitted by : ");
			if(voCA.getAdmittingNurseIsNotNull())
			{
				if (voCA.getAdmittingNurse().getMosIsNotNull())
				{
					sb.append(voCA.getAdmittingNurse().getMos().getName().toString());
				}
				if (voCA.getSysInfoIsNotNull())
				{
					sb.append(" on: ");
					sb.append(voCA.getSysInfo().getCreationDateTime().toString());
				}
			}			

			if (voCA.getDischargedByIsNotNull())
			{
				sb.append(" Discharged By: ");
				sb.append(voCA.getDischargedBy().getName().toString());

				sb.append(" on: ");
				if (voCA.getDischargedDateTimeIsNotNull())
					sb.append(voCA.getDischargedDateTime().toString());
			}
		}
		
		return sb.toString();
	}

	private Boolean iterateCarePlanCollection(CarePlanCollection carePlColl)
	{
		if(carePlColl == null)
			return false;
		for(int i = 0; i < carePlColl.size();i++)
		{
			if(carePlColl.get(i).getCurrentCarePlanStatusIsNotNull() && carePlColl.get(i).getCurrentCarePlanStatus().getStatusIsNotNull()
					&& carePlColl.get(i).getCurrentCarePlanStatus().getStatus().equals(CarePlanStatus.ACTIVE))
				return true;
				
		}
		return false;
		
	}
	private void populateScreenFromData(ClinicalAdmissionVo clinAdmVo,AdmissionDetailVo admdetVo, CareContextShortVo voCCShort )
	{
		clearInstanceControls();
		
		if(voCCShort.getPasEvent() != null)
		{
			form.txtDateTime().setValue(voCCShort.getPasEvent().getEventDateTimeIsNotNull() ? voCCShort.getPasEvent().getEventDateTime().toString() : "");
			
			if(voCCShort.getPasEvent().getConsultantIsNotNull() && voCCShort.getPasEvent().getConsultant().getMosIsNotNull())
				form.txtConsultant().setValue(voCCShort.getPasEvent().getConsultant().getMos().getIMosName());
			else
				form.txtConsultant().setValue("");
			
			form.txtWard().setValue(voCCShort.getPasEvent().getLocationIsNotNull() ? voCCShort.getPasEvent().getLocation().getIItemText(): "");
			
			if(admdetVo != null && admdetVo.getSourceOfAdmissionIsNotNull())
				form.txtSource().setValue(admdetVo.getSourceOfAdmission().getIItemText());
			else
				form.txtSource().setValue("");
				
			//form.getLocalContext().setAllowEditing(true);
		}
		/*else if (form.getGlobalContext().Core.getCurrentCareContextIsNotNull()
			&& form.getGlobalContext().Core.getCurrentCareContext().equals(voCCShort)
			&& voCCShort.getPasEvent() == null)
		{
			engine.showMessage("Patient is not a current inpatient");
			if(ConfigFlag.GEN.RELEASE_MODE.getValue() == true)
				form.getLocalContext().setAllowRecording(false);
			else
				form.getLocalContext().setAllowRecording(true);
		}*/
		if(clinAdmVo != null)
		{
			form.ccAdmittingNurse().setValue(clinAdmVo.getAdmittingNurse());
			form.txtClientsUnderstanding().setValue(clinAdmVo.getClientUnderstanding());
			form.txtSocialCircumstance().setValue(clinAdmVo.getSocialCircumstance());
			form.ccConfirmedBy().setValue(clinAdmVo.getConfirmedBy());
			form.dtimConfirmed().setValue(clinAdmVo.getConfirmedDateTime());
			form.ccDischarged().setValue(clinAdmVo.getDischargedBy());
			form.dtimDischarged().setValue(clinAdmVo.getDischargedDateTime());
		}
		populateGridAction(clinAdmVo);
	}
	private void populateGridAction(ClinicalAdmissionVo clinAdmVo)
	{
		form.grdAction().getRows().clear();
		AdmissionQuestionCollection admQuestColl = (ims.nursing.vo.lookups.LookupHelper.getAdmissionQuestion(domain.getLookupService()));
		
		//if clinAdmVo.getAdmissionChecklist() == null -> populate gridAction only from lookup
		if(clinAdmVo == null || clinAdmVo.getAdmissionChecklist() == null)
		{
			for(int i = 0; i< admQuestColl.size();i++)
			{
				AdmissionChecklistVo checkListVo = new AdmissionChecklistVo();
				grdActionRow row = form.grdAction().getRows().newRow();
				row.setColumnAction(admQuestColl.get(i).getIItemText());
				//wdev-11945
				row.setTooltipForColumnAction(admQuestColl.get(i).getIItemText());
				//---------------
				checkListVo.setChecklistItem(admQuestColl.get(i));
				row.setValue(checkListVo);
				row.setReadOnly(false);
			}
		}
		else
		{			
			for(int i = 0; i< admQuestColl.size();i++)
			{
				
				grdActionRow row = form.grdAction().getRows().newRow();
				AdmissionChecklistVo itemadm = iterateAdmissionChecklisColl(admQuestColl.get(i),clinAdmVo); 
				if( itemadm != null)
				{
					row.setColumnAction(itemadm.getChecklistItem().getIItemText());
					//wdev-11945
					row.setTooltipForColumnAction(itemadm.getChecklistItem().getIItemText());
					//--
					row.setColumnDone(true);
					row.setColumnDoneReadOnly(engine.hasRight(AppRight.NURSING_ADMIN_ROLE) ? false : true);
					row.setColumnDate(itemadm.getCheckedDateTime().getDate().toString());
					row.setColumnTime(itemadm.getCheckedDateTime().getTime().toString());
					row.setColumnHCP(itemadm.getCheckedHCP().getIMosName());
					//wdev-11945
					row.setTooltipForColumnHCP(itemadm.getCheckedHCP().getIMosName());
					//------
					row.setValue(itemadm);
					row.setReadOnly(engine.hasRight(AppRight.NURSING_ADMIN_ROLE) ? false : true);		
				}
				else
				{
					AdmissionChecklistVo checkListVo = new AdmissionChecklistVo();
					row.setColumnAction(admQuestColl.get(i).getIItemText());
					//wdev-11945
					row.setTooltipForColumnAction(admQuestColl.get(i).getIItemText());
					//
					checkListVo.setChecklistItem(admQuestColl.get(i));
					row.setValue(checkListVo);
					row.setReadOnly(false);
				}
			}
		}
	}

	private AdmissionChecklistVo iterateAdmissionChecklisColl(AdmissionQuestion itemLookup, ClinicalAdmissionVo clinAdmVo)
	{
		AdmissionChecklistVoCollection admColl = clinAdmVo.getAdmissionChecklist();
		for(int j = 0; j< admColl.size();j++)
		{
			if(itemLookup.equals(admColl.get(j).getChecklistItem()))
			{
				return admColl.get(j);
			}
								
		}
		return null;
	}
	
	protected void onGrdActionGridCheckBoxClicked(int column, grdActionRow row,	boolean isChecked) throws PresentationLogicException 
	{
		if(isChecked)
		{
			DateTime dt = new DateTime();
			HcpLiteVo hcpVo =   (HcpLiteVo) domain.getHcpLiteUser();
			row.setColumnDate(dt.getDate().toString());
			row.setColumnTime(dt.getTime().toString());
			row.setColumnHCP(hcpVo != null ? hcpVo.getIMosName() : "");
			//wdev-11945
			row.setTooltipForColumnHCP(hcpVo != null ? hcpVo.getIMosName() : "");
			//----
			row.getValue().setCheckedDateTime(dt);
			row.getValue().setCheckedHCP(hcpVo);
		}
		else
		{
			row.setColumnDate(null);
			row.setColumnTime(null);
			row.setColumnHCP(null);
		}
		
	}
	private void updateControlsState()
	{
		if(form.getMode().equals(FormMode.VIEW))
		{
			/*form.btnNew().setVisible((form.getLocalContext().getclinicalAdmission() == null
					|| (form.getLocalContext().getclinicalAdmissionIsNotNull() && form.getLocalContext().getclinicalAdmission().getCareContextIsNotNull()
							&& !form.getLocalContext().getclinicalAdmission().getCareContext().equals(form.getGlobalContext().Core.getCurrentCareContext())))
					&& form.getLocalContext().getAllowRecording() == true);
					*/
			setButtonsVisible(true);
			
			boolean isClinicalAdmissionLinkedToCurrentCC = (form.recbrAdmissions().getValue() instanceof ClinicalAdmissionListVo) && form.getGlobalContext().Core.getCurrentCareContext().equals(form.recbrAdmissions().getValue().getCareContext());
			
			form.btnNew().setEnabled(!form.getLocalContext().getclinicalAdmissionIsNotNull() 
					&& (isCurrentCCLinkedToPASEvent() || Boolean.FALSE.equals(ConfigFlag.GEN.RELEASE_MODE.getValue())));
			
			form.btnEdit().setEnabled(form.getLocalContext().getclinicalAdmission() != null 
					&& form.getLocalContext().getclinicalAdmission().getDischargedDateTime() == null 
					&& form.getLocalContext().getclinicalAdmission().getDischargedBy() == null
					&& (isCurrentCCLinkedToPASEvent() || Boolean.FALSE.equals(ConfigFlag.GEN.RELEASE_MODE.getValue()))
					&& isClinicalAdmissionLinkedToCurrentCC);
			
			form.btnCopy().setEnabled(form.getLocalContext().getclinicalAdmission() == null 
					&&  form.getLocalContext().getpreviousClinicalAdmissionIsNotNull() 
					&& (isCurrentCCLinkedToPASEvent() || Boolean.FALSE.equals(ConfigFlag.GEN.RELEASE_MODE.getValue())));
			
			form.btnConfirm().setEnabled(form.getLocalContext().getclinicalAdmission() != null
					&& form.getLocalContext().getclinicalAdmission().getConfirmedDateTime() == null 
					&& form.getLocalContext().getclinicalAdmission().getConfirmedBy() == null
					&& (isCurrentCCLinkedToPASEvent() || Boolean.FALSE.equals(ConfigFlag.GEN.RELEASE_MODE.getValue()))
					&& isClinicalAdmissionLinkedToCurrentCC);
			
			form.btnDischarge().setEnabled(form.getLocalContext().getclinicalAdmission() != null
					&& form.getLocalContext().getclinicalAdmission().getDischargedDateTime() == null 
					&& form.getLocalContext().getclinicalAdmission().getDischargedBy() == null 
					&& (form.getLocalContext().getclinicalAdmission().getConfirmedDateTime() != null || form.getLocalContext().getclinicalAdmission().getConfirmedBy() != null)
					&& (isCurrentCCLinkedToPASEvent() || Boolean.FALSE.equals(ConfigFlag.GEN.RELEASE_MODE.getValue()))
					&& isClinicalAdmissionLinkedToCurrentCC);
			
			form.btnUndischarge().setEnabled(form.getLocalContext().getclinicalAdmission() != null 
					&& (form.getLocalContext().getclinicalAdmission().getDischargedDateTime() != null || form.getLocalContext().getclinicalAdmission().getDischargedBy() != null)
					&& (isCurrentCCLinkedToPASEvent() || Boolean.FALSE.equals(ConfigFlag.GEN.RELEASE_MODE.getValue()))
					&& isClinicalAdmissionLinkedToCurrentCC && engine.hasRight(AppRight.NURSING_ADMIN_ROLE));
			
			form.ccAdmittingNurse().setEnabled(false);
			form.ccConfirmedBy().setEnabled(false);
			form.ccDischarged().setEnabled(false);
			form.btnSave().setText("Save");
							
		}
		else
		{
			disableControls();
			form.ccAdmittingNurse().isRequired(true);
			form.ccConfirmedBy().isRequired(true);
			form.ccDischarged().isRequired(true);
			form.dtimConfirmed().isRequired();
			form.dtimDischarged().isRequired();
			switch(form.getLocalContext().getbuttonAction())
			{
				case 1:	//New - button was pressed
						
						form.ccAdmittingNurse().setEnabled(true);
						form.grdAction().setReadOnly(false);
						form.txtClientsUnderstanding().setEnabled(true);
						form.txtSocialCircumstance().setEnabled(true);
				break;
				case 2:	//Edit- button was pressed
						if(form.getLocalContext().getclinicalAdmission() != null && form.getLocalContext().getclinicalAdmission().getConfirmedDateTime() == null && form.getLocalContext().getclinicalAdmission().getConfirmedBy() == null)
						{
							form.ccAdmittingNurse().setEnabled(true);
							form.grdAction().setReadOnly(false);
							form.txtClientsUnderstanding().setEnabled(true);
							form.txtSocialCircumstance().setEnabled(true);
						}
						else
							form.grdAction().setReadOnly(false);
					
				break;
				case 3:	//Copy Last - button was pressed
						form.ccAdmittingNurse().setEnabled(true);
						form.grdAction().setReadOnly(false);
						form.txtClientsUnderstanding().setEnabled(true);
						form.txtSocialCircumstance().setEnabled(true);
				break;
				case 4:	//Confirm- button was pressed
						form.ccConfirmedBy().setEnabled(false);
						form.dtimConfirmed().setEnabled(false);
				break;
				case 5: //Discharge- button was pressed
						form.ccDischarged().setEnabled(true);
						form.dtimDischarged().setEnabled(true);
				break;
				case 6:	//Cancel Discharge- button was pressed
						
				break;
			
			}
		}
	}
	private void setButtonsVisible(Boolean b) 
	{
		if(b == null)
			return;
		
		form.btnNew().setVisible(b);
		form.btnEdit().setVisible(b);
		form.btnConfirm().setVisible(b);
		form.btnCopy().setVisible(b);
		form.btnDischarge().setVisible(b);
		form.btnUndischarge().setVisible(b);
	}

	private void disableControls()
	{
		form.ccAdmittingNurse().setEnabled(false);
		form.grdAction().setReadOnly(true);
		form.txtClientsUnderstanding().setEnabled(false);
		form.txtSocialCircumstance().setEnabled(false);
		form.ccConfirmedBy().setEnabled(false);
		form.dtimConfirmed().setEnabled(false);
		form.ccDischarged().setEnabled(false);
		form.dtimDischarged().setEnabled(false);
	}
	private void clearInstanceControls()
	{
		form.txtDateTime().setValue(null);
		form.txtConsultant().setValue(null);
		form.txtWard().setValue(null);
		form.txtSource().setValue(null);
		form.grdAction().getRows().clear();
		form.ccAdmittingNurse().setValue(null);
		form.txtClientsUnderstanding().setValue(null);
		form.txtSocialCircumstance().setValue(null);
		form.ccConfirmedBy().setValue(null);
		form.dtimConfirmed().setValue(null);
		form.ccDischarged().setValue(null);
		form.dtimDischarged().setValue(null);
	}
	public Boolean save() throws PresentationLogicException
	{
		//wdev-13663
		//Check an admission has not been setup since going into edit mode...
		if (form.getGlobalContext().Core.getCurrentCareContextIsNotNull()
			&& form.getLocalContext().getclinicalAdmission() == null)
		{
			if (domain.getClinicalAdmission(form.getGlobalContext().Core.getCurrentCareContext()) != null)
			{
				engine.showMessage("A Clinical Admission has been created by another user. The screen will be refreshed.");
				form.setMode(FormMode.VIEW);
				open();
				return false;
			}
		}

		ClinicalAdmissionVo clinAdmVo = form.getLocalContext().getclinicalAdmission();
		if(clinAdmVo == null)
			clinAdmVo = new ClinicalAdmissionVo();
		
		clinAdmVo = populateDataFromScreen(clinAdmVo);
		
		clinAdmVo.setAdmissionChecklist(populateDataFromGridAction());
		
		String[] str = clinAdmVo.validate(getUIErrors());
		if (str != null && str.length > 0)
		{
			engine.showErrors(str);
			return false;
		}
		try
		{
			clinAdmVo = domain.saveClinicalAdmission(clinAdmVo);
		}
		catch (DomainInterfaceException e)
		{
			engine.showMessage(e.getMessage());
			form.setMode(FormMode.VIEW);
			open();
			return false;
		}
		catch (StaleObjectException e)
		{
			engine.showMessage(ConfigFlag.UI.STALE_OBJECT_MESSAGE.getValue());
			form.setMode(FormMode.VIEW);
			
			form.getLocalContext().setlocalContextForRie(null);//WDEV-13846
			form.getLocalContext().setclinicalAdmission(null);//WDEV-13846
			
			open();
			return false;
		}
		catch (UniqueKeyViolationException e) 
		{
			engine.showErrors(new String[]{"A record with this unique key already exists"});
			form.setMode(FormMode.VIEW);
			return false;
		}
		form.setMode(FormMode.VIEW);
		return true;

		
	}
	private String[] getUIErrors()
	{
		if(form.dtimConfirmed().isEnabled())
		{
			if(form.ccConfirmedBy() == null || form.ccConfirmedBy().getValue() == null || form.dtimConfirmed() == null || form.dtimConfirmed().getValue() == null)
				return new String[]{"Confirmed By and Confirmed Date/Time are mandatory"};
		}
		if(form.dtimDischarged().isEnabled())
		{
			if(form.ccDischarged() == null || form.ccDischarged().getValue() == null || form.dtimDischarged() == null || form.dtimDischarged().getValue() == null)
				return new String[]{"Discharged By and Discharged Date/Time are mandatory"};
			
		}
		
		return null;
	}
	private ClinicalAdmissionVo populateDataFromScreen(ClinicalAdmissionVo tempVo)
	{
		if(tempVo == null)
			tempVo = new ClinicalAdmissionVo();
		
		tempVo.setAdmittingNurse((NurseVo)form.ccAdmittingNurse().getValue());
				
		tempVo.setClientUnderstanding(form.txtClientsUnderstanding().getValue());
		tempVo.setSocialCircumstance(form.txtSocialCircumstance().getValue());
		
		tempVo.setConfirmedBy((MemberOfStaffLiteVo)form.ccConfirmedBy().getValue());
		tempVo.setConfirmedDateTime(form.dtimConfirmed().getValue());
		tempVo.setDischargedBy((MemberOfStaffLiteVo)form.ccDischarged().getValue());
		tempVo.setDischargedDateTime(form.dtimDischarged().getValue());
		tempVo.setCareContext(form.getGlobalContext().Core.getCurrentCareContext());
		if(tempVo.getAuthoringInformation() == null)
		{
			tempVo.setAuthoringInformation(new AuthoringInformationVo());
			tempVo.getAuthoringInformation().setAuthoringDateTime(new DateTime());
			tempVo.getAuthoringInformation().setAuthoringHcp((HcpLiteVo)domain.getHcpLiteUser());
		}
				
		return tempVo;
	}
	
	
	private AdmissionChecklistVoCollection populateDataFromGridAction() 
	{
		AdmissionChecklistVoCollection tempColVo = new AdmissionChecklistVoCollection();
		for(int i = 0; i < form.grdAction().getRows().size();i++)
		{
			if(form.grdAction().getRows().get(i).getColumnDone() == true)
			{
								
				AdmissionChecklistVo admCheckVo = new AdmissionChecklistVo();
				admCheckVo.setChecklistItem(form.grdAction().getRows().get(i).getValue().getChecklistItem());
				admCheckVo.setCheckedDateTime(form.grdAction().getRows().get(i).getValue().getCheckedDateTime());
				admCheckVo.setCheckedHCP(form.grdAction().getRows().get(i).getValue().getCheckedHCP());
				
				tempColVo.add(admCheckVo);
			}
		}
		
		return tempColVo;
		
	}

	@Override
	protected void onRecbrAdmissionsValueChanged() throws PresentationLogicException 
	{
		recordBrowserValueChanged();
	}

	private void recordBrowserValueChanged()
	{
		clearInstanceControls();
		populateGridAction(null);
		form.getLocalContext().setlocalContextForRie(null);//WDEV-13846 
		ClinicalAdmissionVo clinicalAdmission=null;//WDEV-13846 
		if (form.recbrAdmissions().getValue() != null)
		{
			//WDEV-13846 
			if (engine.isRIEMode())
			{
				clinicalAdmission =domain.getClinicalAdmissionById(form.recbrAdmissions().getValue());
			}
			else
			{
				clinicalAdmission = domain.getClinicalAdmission(form.recbrAdmissions().getValue().getCareContext());	
			}
		
			if ((form.recbrAdmissions().getValue() instanceof ClinicalAdmissionListVo) && form.getGlobalContext().Core.getCurrentCareContext().equals(form.recbrAdmissions().getValue().getCareContext()))
			{
				form.getLocalContext().setlocalContextForRie(clinicalAdmission);
			}
				
			openClinicalAdmission(clinicalAdmission);
		}		
		updateControlsState();
	}
}
