//#############################################################################
//#                                                                           #
//#  Copyright (C) <2014>  <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/>.    #
//#                                                                           #
//#############################################################################
//#EOH
// This code was generated by Daniel Laffan using IMS Development Environment (version 1.70 build 3434.21163)
// Copyright (C) 1995-2009 IMS MAXIMS plc. All rights reserved.

package ims.core.forms.assignadtwardandspecialtydialog;

import ims.configuration.gen.ConfigFlag;
import ims.core.vo.LocationLiteVo;
import ims.core.vo.LocationLiteVoCollection;
import ims.core.vo.PendingEmergencyAdmissionLiteVo;
import ims.core.vo.TrackingForADTWardAndSpecialtyDialogVo;
import ims.domain.exceptions.StaleObjectException;
import ims.framework.enumerations.DialogResult;
import ims.framework.exceptions.CodingRuntimeException;
import ims.framework.exceptions.PresentationLogicException;
import ims.framework.utils.DateTime;

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
	{
		open();
	}

	private void open()
	{
		if(form.getGlobalContext().Core.getADTPendingEmergencyAdmission() == null)
			throw new CodingRuntimeException("ADTPendingEmergencyAdmission Global Context is null");
	
		form.getLocalContext().setSelectedWard(form.getGlobalContext().Core.getADTPendingEmergencyAdmission().getAllocatedWard());
		
		form.cmbSpecialty().setValue(null);
		loadHospitals();
	}
	
	private void loadHospitals() 
	{
		form.cmbHospital().clear();
		
		LocationLiteVoCollection hospitals = domain.listActiveHospitals();
		if (hospitals!=null)
		{
			for (LocationLiteVo item: hospitals)
			{
				form.cmbHospital().newRow(item, item.getName());
			}
		}
	}

	private void loadWards()
	{
		form.cmbWard().clear();
		
		if (form.cmbHospital().getValue()!=null)
		{
			LocationLiteVoCollection wards = domain.listWards(form.cmbHospital().getValue());
			if (wards!=null)
			{
				for (LocationLiteVo item : wards) 
				{
					form.cmbWard().newRow(item, item.getName());
				}
			}
		}
	}
	
	private String[] addScreenErrorsToVOErrors(ArrayList<String> screenErrors, String[] arrErrors) 
	{
		String[] arrAllErrors = null;

		if (arrErrors != null)
		{
			arrAllErrors = new String[screenErrors.size() + arrErrors.length];
			for (int i = 0; i < screenErrors.size(); i++)
				arrAllErrors[i] = (String) screenErrors.get(i);

			int i = 0;
			for (int p = screenErrors.size(); p < arrAllErrors.length; p++)
			{
				arrAllErrors[p] = arrErrors[i];
				i++;
			}
		}
		else
		{
			arrAllErrors = new String[screenErrors.size()];

			for (int i = 0; i < screenErrors.size(); i++)
				arrAllErrors[i] = (String) screenErrors.get(i);
		}

		return arrAllErrors;
	}

	@Override
	protected void onBtnSaveClick() throws ims.framework.exceptions.PresentationLogicException
	{
		PendingEmergencyAdmissionLiteVo voEmergencyAdmission = populateDataFormScreen();
		
		ArrayList<String> screenErrors = new ArrayList<String>();
		
		if (form.cmbWard().getValue() == null)
			screenErrors.add("Ward is a mandatory item.");
		if (form.cmbSpecialty().getValue() == null)
			screenErrors.add("Specialty is a mandatory item.");

		String[] arrErrors = voEmergencyAdmission.validate();
		
		String[] arrScreenAndVoErrors = addScreenErrorsToVOErrors(screenErrors, arrErrors);
		if (arrScreenAndVoErrors.length != 0)
		{
			engine.showErrors(arrScreenAndVoErrors);
			return;
		}

		Boolean hasWardChanged = form.getLocalContext().getSelectedWard() == null;
		if(form.getLocalContext().getSelectedWardIsNotNull() && form.getGlobalContext().Core.getADTPendingEmergencyAdmissionIsNotNull() && form.getGlobalContext().Core.getADTPendingEmergencyAdmission().getAllocatedWardIsNotNull())
			hasWardChanged = !form.getLocalContext().getSelectedWard().equals(form.getGlobalContext().Core.getADTPendingEmergencyAdmission().getAllocatedWard());
		
		//wdev-16866
		TrackingForADTWardAndSpecialtyDialogVo trackVo = null;
		if( voEmergencyAdmission != null && voEmergencyAdmission.getID_PendingEmergencyAdmissionIsNotNull())
		{
			trackVo = domain.getTracking(voEmergencyAdmission);
			if( trackVo != null)
			{
				if( trackVo.getBedAvailabilityIsNotNull() )
				{
					trackVo.getBedAvailability().setWard(voEmergencyAdmission.getAllocatedWard());
					trackVo.getBedAvailability().setAvailableDateTime(new DateTime());
				}
			}
			
		}
		//------------
				
		try
		{
			domain.savePendingEmergency(voEmergencyAdmission, hasWardChanged,trackVo);		//wdev-16866
		}
		catch (StaleObjectException e)
		{
			engine.showMessage(ConfigFlag.UI.STALE_OBJECT_MESSAGE.getValue());
			open();
		}
		
		engine.close(DialogResult.OK);
	}
	
	private PendingEmergencyAdmissionLiteVo populateDataFormScreen()
	{
		PendingEmergencyAdmissionLiteVo voEmergencyAdmission = form.getGlobalContext().Core.getADTPendingEmergencyAdmission();

		if(voEmergencyAdmission != null)
		{
			voEmergencyAdmission.setAllocatedWard(form.cmbWard().getValue());

			if(voEmergencyAdmission.getPasEventIsNotNull())
				voEmergencyAdmission.getPasEvent().setSpecialty(form.cmbSpecialty().getValue());
		}
	
		return voEmergencyAdmission;
	}

	@Override
	protected void onBtnCancelClick() throws ims.framework.exceptions.PresentationLogicException
	{
		engine.close(DialogResult.CANCEL);
	}

	@Override
	protected void onCmbHospitalValueChanged() throws PresentationLogicException
	{
		loadWards();
	}
}
