//#############################################################################
//#                                                                           #
//#  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 Rory Fitzpatrick using IMS Development Environment (version 1.54 build 2685.26610)
// Copyright (C) 1995-2007 IMS MAXIMS plc. All rights reserved.

package ims.clinical.forms.preceedingreferral;

import ims.admin.vo.PracticeSearchCriteriaVo;
import ims.clinical.vo.ReferralsRecordingVo;
import ims.clinical.vo.lookups.PrimaryPreceeding;
import ims.clinical.vo.lookups.ReferralCategory;
import ims.clinical.vo.lookups.ReferralSource;
import ims.core.vo.GP;
import ims.core.vo.GpLiteVo;
import ims.core.vo.GpShortVo;
import ims.core.vo.GpShortVoCollection;
import ims.core.vo.Hcp;
import ims.core.vo.HcpCollection;
import ims.core.vo.HcpFilter;
import ims.core.vo.MedicVo;
import ims.core.vo.MemberOfStaffShortVo;
import ims.core.vo.MemberOfStaffShortVoCollection;
import ims.core.vo.OrganisationVo;
import ims.core.vo.OrganisationVoCollection;
import ims.core.vo.OrganisationWithSitesVoCollection;
import ims.core.vo.PersonName;
import ims.core.vo.lookups.HcpDisType;
import ims.framework.enumerations.DialogResult;
import ims.framework.enumerations.FormMode;
import ims.framework.exceptions.PresentationLogicException;

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

	@Override
	protected void onFormOpen(Object[] args) throws ims.framework.exceptions.PresentationLogicException
	{
		form.setMode(form.getGlobalContext().Clinical.getPreceedingReferralDialogModeIsNotNull() ? form.getGlobalContext().Clinical.getPreceedingReferralDialogMode() : FormMode.EDIT);
		open();
	}

	private void open()
	{
		populateScreenFromData();
	}

	private void populateScreenFromData()
	{
		if (form.getGlobalContext().Clinical.getSelectedPreceedingReferralVoIsNotNull())
		{
			ReferralsRecordingVo rrVo = form.getGlobalContext().Clinical.getSelectedPreceedingReferralVo();
			
			form.cmbSourceReferral().setValue(rrVo.getReferralSource());
			
			if (rrVo.getReferredByIsNotNull()) 
			{
				form.qmbReferredBy().setValue(rrVo.getReferredBy());
				if (form.qmbReferredBy().getValue() == null)
				{
					form.qmbReferredBy().newRow(rrVo.getReferredBy(), rrVo.getReferredBy().getName().toString());
					form.qmbReferredBy().setValue(rrVo.getReferredBy());
				}
			}
			else if (rrVo.getReferredByGPIsNotNull()) 
			{
				form.qmbReferredBy().setValue(rrVo.getReferredByGP());
				if (form.qmbReferredBy().getValue() == null)
				{
					form.qmbReferredBy().newRow(rrVo.getReferredByGP(), rrVo.getReferredByGP().getName().toString());
					form.qmbReferredBy().setValue(rrVo.getReferredByGP());
					
				}
			}
			
			form.qmbRefOrganisation().setValue(rrVo.getRefOrgaCode());
			if (form.qmbRefOrganisation().getValue() == null && rrVo.getRefOrgaCodeIsNotNull())
			{
				form.qmbRefOrganisation().newRow(rrVo.getRefOrgaCode(), rrVo.getRefOrgaCode().getName(), null, null);
				form.qmbRefOrganisation().setValue(rrVo.getRefOrgaCode());
			}

			form.cmbPriorty().setValue(rrVo.getReferralPriority());
			form.cmbReason().setValue(rrVo.getReasonForReferral());
			form.dteDecisionRefer().setValue(rrVo.getDateSent());
			form.dteReciptReferral().setValue(rrVo.getDateReceived());
			form.qmbReferredTo().setValue(rrVo.getReferralHCP());
			if (form.qmbReferredTo().getValue() == null && rrVo.getReferralHCP() != null)
			{
				form.qmbReferredTo().newRow(rrVo.getReferralHCP(), rrVo.getReferralHCP().getName().toString());
				form.qmbReferredTo().setValue(rrVo.getReferralHCP());
			}
			form.cmbSpecialtyFuncCode().setValue(rrVo.getSpecialtyFunctionCode());
			form.dteFirstSeen().setValue(rrVo.getDateFirstSeen());
			if (form.getGlobalContext().Clinical.getPreceedingReferralDialogMode().equals(FormMode.EDIT))
				form.customControlAuthoringInfo().setIsRequiredPropertyToControls(true);
			form.customControlAuthoringInfo().setValue(rrVo.getAuthoringInfo());
		}
		else if (form.getGlobalContext().Clinical.getPreceedingReferralDialogMode().equals(FormMode.EDIT))
		{
			form.customControlAuthoringInfo().initializeComponent();
			form.customControlAuthoringInfo().setIsRequiredPropertyToControls(true);
		}

	}

	@Override
	protected void onBtnOKClick() throws ims.framework.exceptions.PresentationLogicException
	{
		ReferralsRecordingVo rrVo = new ReferralsRecordingVo();
		if (form.getGlobalContext().Clinical.getSelectedPreceedingReferralVo() != null)
			rrVo = (ReferralsRecordingVo) form.getGlobalContext().Clinical.getSelectedPreceedingReferralVo().clone();
		
		rrVo.setReferralSource(form.cmbSourceReferral().getValue());
		
		if (form.qmbReferredBy().getValue() instanceof MedicVo) 
		{
			rrVo.setReferredBy((Hcp)form.qmbReferredBy().getValue());
			rrVo.setReferredByGP(null);
		}
		else if (form.qmbReferredBy().getValue() instanceof GpLiteVo) 
		{
			rrVo.setReferredByGP((GpShortVo)form.qmbReferredBy().getValue());
			rrVo.setReferredBy(null);
		}

		rrVo.setRefOrgaCode(form.qmbRefOrganisation().getValue());
		rrVo.setReferralPriority(form.cmbPriorty().getValue());
		rrVo.setReasonForReferral(form.cmbReason().getValue());
		rrVo.setDateSent(form.dteDecisionRefer().getValue());
		rrVo.setDateReceived(form.dteReciptReferral().getValue());
		rrVo.setReferralHCP(form.qmbReferredTo().getValue());
		rrVo.setSpecialtyFunctionCode(form.cmbSpecialtyFuncCode().getValue());
		rrVo.setDateFirstSeen(form.dteFirstSeen().getValue());
		rrVo.setAuthoringInfo(form.customControlAuthoringInfo().getValue());

		rrVo.setPrimaryPreceeding(PrimaryPreceeding.PREECEDING);
		rrVo.setReferralCategory(ReferralCategory.PRECEEDEDEPISODE);

		if (rrVo.getClinicalContact() == null)
			rrVo.setClinicalContact(form.getGlobalContext().Core.getCurrentClinicalContact());
		
		if (rrVo.getCareContext() == null)
			rrVo.setCareContext(form.getGlobalContext().Core.getCurrentCareContext());

		if (rrVo.getCareSpell() == null)
			rrVo.setCareSpell(form.getGlobalContext().Core.getCurrentCareContext().getEpisodeOfCare().getCareSpell());

		
		
		String[] errors = rrVo.validate();
		if(errors != null && errors.length > 0)
		{
			engine.showErrors(errors);
			return;
		}
		form.getGlobalContext().Clinical.setSelectedPreceedingReferralVo(rrVo);
		engine.close(DialogResult.OK);
	}
	
	@Override
	protected void onBtnCancelClick() throws ims.framework.exceptions.PresentationLogicException
	{
		engine.close(DialogResult.CANCEL);
	}
	
	@Override
	protected void onQmbReferredByTextSubmited(String value) throws ims.framework.exceptions.PresentationLogicException
	{
		form.qmbReferredBy().clear();
		
		if (form.cmbSourceReferral().getValue() != null && form.cmbSourceReferral().getValue().equals(ReferralSource.GPREFERRAL))
		{
			GpShortVoCollection gpColl = domain.listGPsBySurname(value);
			if(gpColl != null)
			{
				for (int i = 0; i < gpColl.size(); i++)
					form.qmbReferredBy().newRow(gpColl.get(i), gpColl.get(i).toString());			

				if (gpColl.size() == 1)
				{
					form.qmbReferredBy().setValue(gpColl.get(0));
					loadGPsPractice(gpColl.get(0));
				}
				else if (gpColl.size() > 1)
					form.qmbReferredBy().showOpened();		
			}		
		}
		else
		{
			HcpFilter filter = new HcpFilter();
			PersonName name = new PersonName();
			name.setSurname(value);
			filter.setQueryName(name);
			filter.setHcpType(HcpDisType.MEDICAL);
			HcpCollection coll = domain.listHcps(filter, null);//HcpDisType.MEDICAL);
			if(coll != null)
			{
				for (int i = 0; i < coll.size(); i++)
					form.qmbReferredBy().newRow(coll.get(i), coll.get(i).toString());			

				if (coll.size() == 1)
					form.qmbReferredBy().setValue(coll.get(0));
				else if (coll.size() > 1)
					form.qmbReferredBy().showOpened();		
			}		
		}
	}
	
	@Override
	protected void onQmbRefOrganisationTextSubmited(String value) throws ims.framework.exceptions.PresentationLogicException
	{
		form.qmbRefOrganisation().clear();
		
		if (form.cmbSourceReferral().getValue() != null && form.cmbSourceReferral().getValue().equals(ReferralSource.GPREFERRAL))
		{
			PracticeSearchCriteriaVo voGP = new PracticeSearchCriteriaVo();
			voGP.setName(value);
			voGP.setIsActive(new Boolean(true));
			
			OrganisationWithSitesVoCollection voColl = domain.listPractice(voGP);
			for (int i = 0 ; i < voColl.size() ; i++)
			{
				if (voColl.get(i).getIsActiveIsNotNull() && voColl.get(i).getIsActive().booleanValue())
					form.qmbRefOrganisation().newRow(voColl.get(i), voColl.get(i).getName());

				if (voColl.size() == 1)
					form.qmbRefOrganisation().setValue(voColl.get(0));
				else if (voColl.size() > 1)
					form.qmbRefOrganisation().showOpened();		
			}
		}
		else
		{
			OrganisationVo voOrg = new OrganisationVo();
			voOrg.setName(value);
			
			OrganisationVoCollection voColl = domain.listOrganisation(voOrg);
			for (int i = 0 ; i < voColl.size() ; i++)
			{
				if (voColl.get(i).getIsActiveIsNotNull() && voColl.get(i).getIsActive().booleanValue())
					form.qmbRefOrganisation().newRow(voColl.get(i), voColl.get(i).getName());

				if (voColl.size() == 1)
					form.qmbRefOrganisation().setValue(voColl.get(0));
				else if (voColl.size() > 1)
					form.qmbRefOrganisation().showOpened();		
			}
		}
	}

	@Override
	protected void onQmbReferredToTextSubmited(String value) throws PresentationLogicException 
	{
		form.qmbReferredTo().clear();
		
		MemberOfStaffShortVo voMOS = new MemberOfStaffShortVo();
		PersonName personName = new PersonName();
		personName.setSurname(value);
		voMOS.setName(personName);
		voMOS.setIsActive(Boolean.TRUE);
		
		MemberOfStaffShortVoCollection coll = domain.listMembersOfStaff(voMOS);
		if(coll != null)
		{
			for (int i = 0; i < coll.size(); i++)
				form.qmbReferredTo().newRow(coll.get(i), coll.get(i).toString());			

			if (coll.size() == 1)
				form.qmbReferredTo().setValue(coll.get(0));
			else if (coll.size() > 1)
				form.qmbReferredTo().showOpened();		
		}		
	}

	@Override
	protected void onQmbReferredByValueChanged() throws PresentationLogicException
	{
		if (form.qmbReferredBy().getValue() instanceof GpShortVo)
		{
			loadGPsPractice((GpShortVo)form.qmbReferredBy().getValue());
		}
	}

	private void loadGPsPractice(GpShortVo vo) 
	{
		GP gpVo = domain.getGP(vo);
		if (gpVo.getPracticesIsNotNull() && gpVo.getPractices().size() > 0)
		{
			for (int i = 0 ; i < gpVo.getPractices().size() ; i++)
			{
				if (gpVo.getPractices().get(i).getIsPrimaryPracticeIsNotNull() &&
					gpVo.getPractices().get(i).getIsPrimaryPractice().booleanValue() )
				{
					form.qmbRefOrganisation().newRow(gpVo.getPractices().get(i).getPractice(), gpVo.getPractices().get(i).getPractice().getName(), null, null);
					form.qmbRefOrganisation().setValue(gpVo.getPractices().get(i).getPractice());
				}
			}
		}
	}

	@Override
	protected void onCmbSourceReferralValueChanged() throws PresentationLogicException 
	{
		form.qmbReferredBy().clear();
		form.qmbReferredBy().setValue(null);
		form.qmbRefOrganisation().setValue(null);
		form.qmbRefOrganisation().clear();
	}

}
