package com.gentics.mesh.core.data.node.field.list;

import static com.gentics.mesh.core.data.relationship.GraphRelationships.HAS_ITEM;
import static com.gentics.mesh.core.data.relationship.GraphRelationships.HAS_LIST;

import java.util.List;

import com.gentics.mesh.core.data.GraphFieldContainer;
import com.gentics.mesh.core.data.MeshVertex;
import com.gentics.mesh.core.data.node.field.GraphField;
import com.gentics.mesh.core.data.node.field.nesting.ListableGraphField;
import com.gentics.mesh.core.rest.node.field.Field;

/**
 * Abstract class for referencing field lists.
 *
 * @param <T>
 *            Type the listed field
 * @param <RM>
 *            Rest model type for the field
 * @param <U>
 *            Type of element that is referenced
 */
public abstract class AbstractReferencingGraphFieldList<T extends ListableGraphField, RM extends Field, U> extends AbstractGraphFieldList<T, RM, U> {

	@Override
	public long getSize() {
		return outE(HAS_ITEM).has(getListType()).count();
	}

	protected T addItem(String key, MeshVertex vertex) {
		return addFramedEdge(HAS_ITEM, vertex, getListType());
	}

	@Override
	public void removeAll() {
		outE(HAS_ITEM).removeAll();
	}

	@Override
	public List<? extends T> getList() {
		return outE(HAS_ITEM).has(getListType()).toListExplicit(getListType());
	}

	@Override
	public void removeField(GraphFieldContainer container) {
		// Detach the list from the given graph field container
		container.unlinkOut(this, HAS_LIST);

		// Remove the field if no more containers are attached to it
		if (in(HAS_LIST).count() == 0) {
			delete(null);
		}
	}

	@Override
	public GraphField cloneTo(GraphFieldContainer container) {
		container.linkOut(this, HAS_LIST);
		return container.getList(getClass(), getFieldKey());
	}

	public void removeField() {
		delete(null);
	}
}

@@ -231,24 +231,60 @@
 a.util.List;
+%0Aimport java.util.stream.Collectors;
 %0A%0Aimport com
@@ -1086,22 +1086,24 @@
 ex) %7B%0A%09%09
-return
+T edge =
  addFram
@@ -1135,32 +1135,72 @@
 getListType());%0A
+%09%09edge.setFieldKey(key);%0A%09%09return edge;%0A
 %09%7D%0A%0A%09@Override%0A%09
@@ -1306,30 +1306,48 @@
 tList() %7B%0A%09%09
-return
+List%3C? extends T%3E list =
  outE(HAS_IT
@@ -1396,24 +1396,339 @@
 istType());%0A
+%09%09return list.stream().sorted((a, b) -%3E %7B%0A%09%09%09String bk = b.getFieldKey();%0A%09%09%09String ak = a.getFieldKey();%0A%09%09%09if (bk == null) %7B%0A%09%09%09%09bk = %220%22;%0A%09%09%09%7D%0A%09%09%09if (ak == null) %7B%0A%09%09%09%09ak = %220%22;%0A%09%09%09%7D%0A%09%09%09long bv = Long.valueOf(bk);%0A%09%09%09long av = Long.valueOf(ak);%0A%09%09%09return Long.compare(av, bv);%0A%09%09%7D).collect(Collectors.toList());%0A
 %09%7D%0A%0A%09@Overri

Fix order of elements in micronode list. Fixes #469