if (!canGetValueForBinding("listItemIDKeyPath")) {
throw new IllegalArgumentException("You must specify 'listItemIDKeyPath' if you specify 'list'.");
}
String listItemIDKeyPath = (String) valueForBinding("listItemIDKeyPath");
Object listItemIDArrayObj = request.formValues().objectForKey(_sortOrderKeyName + "[]");
NSArray listItemIDArray;
if (listItemIDArrayObj instanceof NSArray) {
listItemIDArray = (NSArray) listItemIDArrayObj;
}
else if (listItemIDArrayObj instanceof String) {
String listItemIDStr = (String) listItemIDArrayObj;
listItemIDArray = new NSArray(listItemIDStr);
}
else {
throw new IllegalArgumentException("Unknown list item ID array " + listItemIDArrayObj);
}
NSArray list = (NSArray) valueForBinding("list");
boolean mutableList = (list instanceof NSMutableArray);
NSMutableArray reorderedList;
if (mutableList) {
reorderedList = (NSMutableArray) list;
}
else {
reorderedList = new NSMutableArray();
}
int startIndex = 0;
// If we're starting at an index > 0, add the initial objects
if (canGetValueForBinding("startIndex")) {
Number startIndexNumber = (Number) valueForBinding("startIndex");
startIndex = startIndexNumber.intValue();
if (!mutableList) {
for (int i = 0; i < startIndex; i++) {
reorderedList.addObject(list.objectAtIndex(i));
}
}
}
// Add the reordered objects
int listItemIDCount = listItemIDArray.count();
for (int listItemIDIndex = 0; listItemIDIndex < listItemIDCount; listItemIDIndex++) {
String itemID = (String) listItemIDArray.objectAtIndex(listItemIDIndex);
NSRange itemPageRange;
if (mutableList) {
itemPageRange = new NSRange(startIndex + listItemIDIndex, listItemIDCount - listItemIDIndex);
}
else {
itemPageRange = new NSRange(startIndex, listItemIDCount);
}
NSArray itemPageArray = list.subarrayWithRange(itemPageRange);
EOQualifier itemIDQualifier = new EOKeyValueQualifier(listItemIDKeyPath, EOQualifier.QualifierOperatorEqual, itemID);
NSArray matchingItems = EOQualifier.filteredArrayWithQualifier(itemPageArray, itemIDQualifier);
if (matchingItems.count() == 0) {
throw new NoSuchElementException("There was no item that matched the ID '" + itemID + "' in " + list + ".");
}
else if (matchingItems.count() > 1) {
throw new IllegalStateException("There was more than one item that matched the ID '" + itemID + "' in " + list + ".");
}
Object replacingItem = matchingItems.objectAtIndex(0);
if (mutableList) {
int replacedItemIndex = itemPageRange.location();
Object replacedItem = reorderedList.objectAtIndex(replacedItemIndex);
if (replacedItem != replacingItem) {
int replacingItemIndex = replacedItemIndex + itemPageArray.indexOfObject(replacingItem);