/*
HMArrayController.m

Author: Makoto Kinoshita

Copyright 2004-2006 The Shiira Project. All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted 
provided that the following conditions are met:

  1. Redistributions of source code must retain the above copyright notice, this list of conditions 
  and the following disclaimer.

  2. Redistributions in binary form must reproduce the above copyright notice, this list of 
  conditions and the following disclaimer in the documentation and/or other materials provided 
  with the distribution.

THIS SOFTWARE IS PROVIDED BY THE SHIIRA PROJECT ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, 
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE SHIIRA PROJECT OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, 
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, 
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING 
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 
POSSIBILITY OF SUCH DAMAGE.
*/

#import "HMArrayController.h"

// Pboard type
NSString*   HMArrayControllerPboardType = @"HMArrayControllerPboardType";

@implementation HMArrayController

//--------------------------------------------------------------//
#pragma mark -- Initialize --
//--------------------------------------------------------------//

- (void)dealloc
{
    [_indexKeyPath release], _indexKeyPath = nil;
    
    [super dealloc];
}

//--------------------------------------------------------------//
#pragma mark -- Key path --
//--------------------------------------------------------------//

- (NSString*)indexKeyPath
{
    return _indexKeyPath;
}

- (void)setIndexKeyPath:(NSString*)keyPath
{
    [_indexKeyPath release], _indexKeyPath = nil;
    _indexKeyPath = [keyPath copy];
    
    // Set sort descriptors
    NSSortDescriptor*   sortDescriptor;
    sortDescriptor = [[NSSortDescriptor alloc] initWithKey:_indexKeyPath ascending:YES];
    [self setSortDescriptors:[NSArray arrayWithObject:sortDescriptor]];
    [sortDescriptor release];
}

//--------------------------------------------------------------//
#pragma mark -- Object management --
//--------------------------------------------------------------//

- (void)insertObject:(id)object atArrangedObjectIndex:(unsigned int)index
{
    [super insertObject:object atArrangedObjectIndex:index];
    
    // Check index key
    if (!_indexKeyPath) {
        return;
    }
    
    // Get arranged objects
    NSArray*    arrangedObjects;
    arrangedObjects = [self arrangedObjects];
    
    // Get current index value
    unsigned int    ind = 0;
    if (index > 0) {
        id  object;
        object = [arrangedObjects objectAtIndex:index - 1];
        ind = [[object valueForKey:_indexKeyPath] unsignedIntValue] + 1;
    }
    
    // Update object's index
    unsigned int    i;
    for (i = index; i < [arrangedObjects count]; i++) {
        id  object;
        object = [arrangedObjects objectAtIndex:i];
        [object setValue:[NSNumber numberWithUnsignedInt:ind++] forKey:_indexKeyPath];
    }
}

- (void)insertObjects:(NSArray*)objects atArrangedObjectIndexes:(NSIndexSet*)indexes
{
    [super insertObjects:objects atArrangedObjectIndexes:indexes];
}

//--------------------------------------------------------------//
#pragma mark -- NSTableView data source --
//--------------------------------------------------------------//

- (int)numberOfRowsInTableView:(NSTableView*)tableView
{
    return 0;
}

- (id)tableView:(NSTableView*)tableView 
        objectValueForTableColumn:(NSTableColumn*)tableColumn 
        row:(int)rowIndex
{
    return nil;
}

- (BOOL)tableView:(NSTableView*)tableView 
        writeRowsWithIndexes:(NSIndexSet*)rowIndexes 
        toPasteboard:(NSPasteboard*)pboard
{
    // Declare types
    [pboard declareTypes:[NSArray arrayWithObject:HMArrayControllerPboardType] owner:nil];
    
    // Get arranged objects
    NSArray*    arrangedObjects;
    arrangedObjects = [self arrangedObjects];
    
    // Get URI representations
    NSMutableArray* URIReps;
    unsigned int    index;
    URIReps = [NSMutableArray array];
    index = [rowIndexes firstIndex];
    _isCopyable = YES;
    do {
        // Check index
        if (index >= [arrangedObjects count]) {
            break;
        }
        
        // Get managed object
        NSManagedObject*    object;
        object = [arrangedObjects objectAtIndex:index];
        if (!object) {
            continue;
        }
        
        // Get URI representation
        NSString*   URIRep;
        URIRep = [[[object objectID] URIRepresentation] absoluteString];
        if (!URIRep) {
            continue;
        }
        
        // Add URI representation
        [URIReps addObject:URIRep];
        
        // Check copying protocol
        if (![object conformsToProtocol:@protocol(NSCopying)]) {
            _isCopyable = NO;
        }
    } while ((index = [rowIndexes indexGreaterThanIndex:index]) != NSNotFound);
    
    if ([URIReps count] == 0) {
        return NO;
    }
    
    // Set URI representations
    [pboard setPropertyList:URIReps forType:HMArrayControllerPboardType];
    
    return YES;
}

- (NSDragOperation)tableView:(NSTableView*)tableView 
        validateDrop:(id <NSDraggingInfo>)info 
        proposedRow:(int)row 
        proposedDropOperation:(NSTableViewDropOperation)operation
{
    // Get pboard
    NSPasteboard*   pboard;
    pboard = [info draggingPasteboard];
    if (!pboard) {
        return NSDragOperationNone;
    }
    
    // Check pboard type
    if (![[pboard types] containsObject:HMArrayControllerPboardType]) {
        return NSDragOperationNone;
    }
    
    // Check operation
    if (operation == NSTableViewDropOn) {
        return NSDragOperationNone;
    }
    
    // Check modifier key
    if (_isCopyable) {
        NSEvent*    event;
        event = [[NSApplication sharedApplication] currentEvent];
        if ([event modifierFlags] & NSAlternateKeyMask) {
            return NSDragOperationCopy;
        }
    }
    
    return NSDragOperationMove;
}

- (BOOL)tableView:(NSTableView*)tableView 
        acceptDrop:(id <NSDraggingInfo>)info 
        row:(int)row 
        dropOperation:(NSTableViewDropOperation)operation
{
    // Get pboard
    NSPasteboard*   pboard;
    pboard = [info draggingPasteboard];
    if (!pboard) {
        return NO;
    }
    
    // Get URI representations
    NSArray*    URIReps;
    URIReps = [pboard propertyListForType:HMArrayControllerPboardType];
    if (!URIReps || ![URIReps isKindOfClass:[NSArray class]]) {
        return NO;
    }
    if ([URIReps count] == 0) {
        return NO;
    }
    
    // Check modifier key
    BOOL    isCopying = NO;
    if (_isCopyable) {
        NSEvent*    event;
        event = [[NSApplication sharedApplication] currentEvent];
        if ([event modifierFlags] & NSAlternateKeyMask) {
            isCopying = YES;
        }
    }
    
    // Get arranged objects
    NSArray*    arrangedObjects;
    arrangedObjects = [self arrangedObjects];
    
    // Get managed object context
    NSManagedObjectContext*         context;
    NSPersistentStoreCoordinator*   store;
    context = [self managedObjectContext];
    store = [context persistentStoreCoordinator];
    if (!store) {
        return NO;
    }
    
    // Get above object index
    unsigned int    index = row;
    if (row > 0) {
        NSManagedObject*    object;
        object = [arrangedObjects objectAtIndex:row - 1];
        index = [[object valueForKey:_indexKeyPath] unsignedIntValue] + 1;
    }
    
    // Get managed objects
    NSMutableArray* objects;
    NSEnumerator*   enumerator;
    NSString*       URIRep;
    objects = [NSMutableArray array];
    enumerator = [URIReps objectEnumerator];
    while (URIRep = [enumerator nextObject]) {
        // Get managed object
        NSManagedObjectID*  objectId;
        NSManagedObject*    object;
        objectId = [store managedObjectIDForURIRepresentation:[NSURL URLWithString:URIRep]];
        object = [context objectWithID:objectId];
        if (!object) {
            continue;
        }
        
        // For copying
        if (isCopying) {
            object = [object copy];
        }
        
        // Set index value
        [object setValue:[NSNumber numberWithUnsignedInt:index++] forKey:_indexKeyPath];
        
        // Add managed object
        [objects addObject:object];
    }
    
    // Reset index values for below dragged objects
    unsigned int    i;
    for (i = row; i < [arrangedObjects count]; i++) {
        // Get managed object from arranged object
        NSManagedObject*    object;
        object = [arrangedObjects objectAtIndex:i];
        if ([objects containsObject:object]) {
            continue;
        }
        
        // Set index value
        [object setValue:[NSNumber numberWithUnsignedInt:index++] forKey:_indexKeyPath];
    }
    
    // Reload data
    [self rearrangeObjects];
    
    return YES;
}

@end
