@Override
public Node remove(int index) {
if (index < 0 || index >= size())
throw new IndexOutOfBoundsException();
Relationship currentEntryRelation = underlyingNode
.getSingleRelationship(RelTypes.FIRST_ELEMENT,
Direction.OUTGOING);
Node currentEntry = currentEntryRelation.getEndNode();
Node currentNode = currentEntry.getSingleRelationship(
RelTypes.LIST_ENTRY, Direction.OUTGOING).getEndNode();
Relationship lastEntryRelation = underlyingNode.getSingleRelationship(
RelTypes.LAST_ELEMENT, Direction.OUTGOING);
Node lastEntry = lastEntryRelation.getEndNode();
if (index == 0) {
currentEntryRelation.delete();
if (currentEntry.getId() == lastEntry.getId()) {
lastEntryRelation.delete();
Relationship entryRelation = currentEntry
.getSingleRelationship(RelTypes.LIST_ENTRY,
Direction.OUTGOING);
entryRelation.delete();
currentEntry.delete();
underlyingNode.setProperty(INDEX_SIZE, 0);
} else {
Relationship nextEntryRelation = currentEntry
.getSingleRelationship(RelTypes.NEXT_ELEMENT,
Direction.OUTGOING);
Node nextEntry = nextEntryRelation.getEndNode();
nextEntryRelation.delete();
Relationship entryRelation = currentEntry
.getSingleRelationship(RelTypes.LIST_ENTRY,
Direction.OUTGOING);
entryRelation.delete();
currentEntry.delete();
underlyingNode.createRelationshipTo(nextEntry,
RelTypes.FIRST_ELEMENT);
int i = (Integer) underlyingNode.getProperty(INDEX_SIZE);
underlyingNode.setProperty(INDEX_SIZE, i-1);
}
} else {
for (int i = 0; i < index; i++) {
currentEntryRelation = currentEntry.getSingleRelationship(
RelTypes.NEXT_ELEMENT, Direction.OUTGOING);
currentEntry = currentEntryRelation.getEndNode();
}
currentNode = currentEntry.getSingleRelationship(
RelTypes.LIST_ENTRY, Direction.OUTGOING).getEndNode();
Node prevEntry = currentEntryRelation.getStartNode();
currentEntryRelation.delete();
if (currentEntry.getId() == lastEntry.getId()) {
lastEntryRelation.delete();
underlyingNode.createRelationshipTo(prevEntry,
RelTypes.LAST_ELEMENT);
Relationship entryRelation = currentEntry
.getSingleRelationship(RelTypes.LIST_ENTRY,
Direction.OUTGOING);
entryRelation.delete();
currentEntry.delete();
int i = (Integer) underlyingNode.getProperty(INDEX_SIZE);
underlyingNode.setProperty(INDEX_SIZE, i-1);
} else {
Relationship nextEntryRelation = currentEntry
.getSingleRelationship(RelTypes.NEXT_ELEMENT,
Direction.OUTGOING);
Node nextEntry = nextEntryRelation.getEndNode();
nextEntryRelation.delete();
Relationship entryRelation = currentEntry
.getSingleRelationship(RelTypes.LIST_ENTRY,
Direction.OUTGOING);
entryRelation.delete();
currentEntry.delete();
prevEntry
.createRelationshipTo(nextEntry, RelTypes.NEXT_ELEMENT);
int i = (Integer) underlyingNode.getProperty(INDEX_SIZE);
underlyingNode.setProperty(INDEX_SIZE, i-1);