package at.medevit.elexis.agenda.ui.function;

import org.eclipse.jface.viewers.ISelectionProvider;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.swt.chromium.Browser;
import org.eclipse.swt.chromium.BrowserFunction;

import ch.elexis.core.model.IAppointment;
import ch.elexis.core.model.IContact;
import ch.elexis.core.model.IPatient;
import ch.elexis.core.services.holder.ContextServiceHolder;
import ch.elexis.core.services.holder.CoreModelServiceHolder;

public class SingleClickFunction extends BrowserFunction {
	
	private ISelectionProvider selectionProvider;
	
	public SingleClickFunction(Browser browser, String name){
		super(browser, name);
	}
	
	@Override
	public Object function(Object[] arguments){
		if (arguments.length == 1) {
			IAppointment termin = CoreModelServiceHolder.get()
				.load((String) arguments[0], IAppointment.class).orElse(null);
			ContextServiceHolder.get().getRootContext().setTyped(termin);
			if (selectionProvider != null) {
				selectionProvider.setSelection(new StructuredSelection(termin));
			}
			IContact contact = termin.getContact();
			if (contact != null && contact.isPatient()) {
				ContextServiceHolder.get().setActivePatient(
					CoreModelServiceHolder.get().load(contact.getId(), IPatient.class).get());
			}
		} else if (arguments.length == 0) {
			if (selectionProvider != null) {
				selectionProvider.setSelection(StructuredSelection.EMPTY);
			}
		}
		return null;
	}
	
	public void setSelectionProvider(ISelectionProvider selectionProvider){
		this.selectionProvider = selectionProvider;
	}
}

@@ -885,16 +885,42 @@
 (null);%0A
+%09%09%09if (termin != null) %7B%0A%09
 %09%09%09Conte
@@ -975,24 +975,25 @@
 termin);%0A%09%09%09
+%09
 if (selectio
@@ -1005,32 +1005,33 @@
 ider != null) %7B%0A
+%09
 %09%09%09%09selectionPro
@@ -1086,18 +1086,20 @@
 n));%0A%09%09%09
+%09
 %7D%0A
+%09
 %09%09%09ICont
@@ -1132,24 +1132,25 @@
 ntact();%0A%09%09%09
+%09
 if (contact 
@@ -1179,32 +1179,33 @@
 atient()) %7B%0A%09%09%09%09
+%09
 ContextServiceHo
@@ -1233,16 +1233,17 @@
 atient(%0A
+%09
 %09%09%09%09%09Cor
@@ -1314,16 +1314,22 @@
 get());%0A
+%09%09%09%09%7D%0A
 %09%09%09%7D%0A%09%09%7D

fix null appointment access in agenda web SingleClickFunction