package org.openlca.app.navigation;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.swt.dnd.DragSourceEvent;
import org.eclipse.swt.dnd.Transfer;
import org.eclipse.ui.navigator.CommonDragAdapterAssistant;
import org.openlca.app.components.ModelTransfer;
import org.openlca.app.navigation.elements.CategoryElement;
import org.openlca.app.navigation.elements.ModelElement;
import org.openlca.core.model.descriptors.Descriptor;

public class NavigationDragAssistant extends CommonDragAdapterAssistant {

	@Override
	public void dragStart(DragSourceEvent anEvent,
			IStructuredSelection aSelection) {
		anEvent.doit = true;
		Iterator<?> it = aSelection.iterator();
		while (it.hasNext() && anEvent.doit) {
			Object o = it.next();
			if (!(o instanceof ModelElement || o instanceof CategoryElement)) {
				anEvent.doit = false;
			}
		}
	}

	@Override
	public Transfer[] getSupportedTransferTypes() {
		return new Transfer[] { ModelTransfer.getInstance() };
	}

	@Override
	public boolean setDragData(DragSourceEvent anEvent,
			IStructuredSelection aSelection) {
		boolean canBeDropped = true;
		Iterator<?> it = aSelection.iterator();
		List<Descriptor> components = new ArrayList<>();
		while (it.hasNext() && canBeDropped) {
			Object o = it.next();
			if (!(o instanceof ModelElement || o instanceof CategoryElement)) {
				canBeDropped = false;
			} else {
				if (o instanceof ModelElement navElem) {
					var comp = navElem.getContent();
					if (comp != null)
						components.add(comp);
				}
			}
		}
		if (canBeDropped) {
			Object[] data = new Object[components.size()];
			for (int i = 0; i < components.size(); i++) {
				data[i] = components.get(i);
			}
			anEvent.data = data;
		}
		return canBeDropped;
	}
}

@@ -647,36 +647,31 @@
 SourceEvent 
-anE
+e
 vent,
-%0A%09%09%09
+ 
 IStructuredS
@@ -671,34 +671,33 @@
 cturedSelection 
-aS
+s
 election) %7B%0A%09%09an
@@ -694,19 +694,17 @@
 on) %7B%0A%09%09
-anE
+e
 vent.doi
@@ -719,122 +719,138 @@
 ;%0A%09%09
-Iterator%3C?%3E it = aSelection.iterator();%0A%09%09while (it.hasNext() && anEvent.doit) %7B%0A%09%09%09Object o = it.next();
+for (var o : selection) %7B%0A%09%09%09if (o instanceof ModelElement modElem) %7B%0A%09%09%09%09if (!modElem.isFromLibrary())%0A%09%09%09%09%09continue;%0A%09%09%09%7D
 %0A%09%09%09if 
-(!
 (o i
@@ -863,64 +863,97 @@
 eof 
-ModelElement %7C%7C o instanceof CategoryElem
+CategoryElement catElem) %7B%0A%09%09%09%09if (!catElem.hasLibraryCont
 ent
+(
 ))
- %7B
 %0A%09%09%09%09
-anE
+%09continue;%0A%09%09%09%7D%0A%09%09%09e
 vent
@@ -966,25 +966,30 @@
 = false;%0A%09%09%09
-%7D
+break;
 %0A%09%09%7D%0A%09%7D%0A%0A%09@O
@@ -1072,11 +1072,9 @@
 er%5B%5D
- %7B 
+%7B
 Mode
@@ -1096,17 +1096,16 @@
 stance()
- 
 %7D;%0A%09%7D%0A%0A%09
@@ -1167,17 +1167,16 @@
 nEvent,%0A
-%09
 %09%09IStruc

disable dnd for library elements