package ch.elexis.core.ui.medication.handlers;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.ui.handlers.HandlerUtil;

import ch.elexis.core.model.IPatient;
import ch.elexis.core.model.IPrescription;
import ch.elexis.core.services.holder.ContextServiceHolder;
import ch.elexis.core.ui.medication.views.MedicationTableViewerItem;
import ch.elexis.core.ui.util.CreatePrescriptionHelper;

public class DispenseHandler extends AbstractHandler {
	
	@SuppressWarnings("unchecked")
	@Override
	public Object execute(ExecutionEvent event) throws ExecutionException{
		Optional<IPatient> patient = ContextServiceHolder.get().getActivePatient();
		if (!patient.isPresent()) {
			return null;
		}
		
		List<IPrescription> prescRecipes = new ArrayList<IPrescription>();
		
		ISelection selection =
			HandlerUtil.getActiveWorkbenchWindow(event).getActivePage().getSelection();
		if (!selection.isEmpty()) {
			IStructuredSelection strucSelection = (IStructuredSelection) selection;
			List<MedicationTableViewerItem> mtvItems = strucSelection.toList();
			for (MedicationTableViewerItem mtvItem : mtvItems) {
				IPrescription p = mtvItem.getPrescription();
				if (p != null) {
					prescRecipes.add(p);
				}
			}
		}
		for (IPrescription prescription : prescRecipes) {
			CreatePrescriptionHelper prescriptionHelper =
				new CreatePrescriptionHelper(null, HandlerUtil.getActiveShell(event));
			prescriptionHelper.selfDispense(prescription);
		}
		return null;
	}
	
}

@@ -413,24 +413,112 @@
 ndlerUtil;%0A%0A
+import ch.elexis.core.common.ElexisEventTopics;%0Aimport ch.elexis.core.model.IEncounter;%0A
 import ch.el
@@ -1824,16 +1824,169 @@
 n);%0A%09%09%7D%0A
+%09%09ContextServiceHolder.get().getTyped(IEncounter.class).ifPresent(%0A%09%09%09enc -%3E ContextServiceHolder.get().postEvent(ElexisEventTopics.EVENT_UPDATE, enc));%0A
 %09%09return

add update event to medication DispenseHandler