//
//  SKIndexCommand.m
//  Skim
//
//  Created by Christiaan Hofman on 6/4/08.


#import "SKIndexCommand.h"
#import <Quartz/Quartz.h>
#import "PDFPage_SKExtensions.h"
#import "PDFSelection_SKExtensions.h"


@implementation SKIndexCommand

- (id)performDefaultImplementation {
    id dP = [self directParameter];
    id dPO = nil;
    if ([dP isKindOfClass:[NSArray class]] == NO)
        dPO = [dP objectsByEvaluatingSpecifier];
    
    NSDictionary *args = [self evaluatedArguments];
    PDFPage *page = [args objectForKey:@"Page"];
    BOOL last = [[args objectForKey:@"Last"] boolValue];
    NSUInteger idx = NSNotFound;
    
    if ([dPO isKindOfClass:[NSDocument class]]) {
        idx = [[NSApp orderedDocuments] indexOfObjectIdenticalTo:dPO];
    } else if ([dPO isKindOfClass:[PDFPage class]]) {
        idx = [dPO pageIndex];
    } else if ([dPO isKindOfClass:[PDFAnnotation class]]) {
        idx = [[((id)page ?: (id)[page containingDocument]) valueForKey:@"notes"] indexOfObjectIdenticalTo:dPO];
    } else {
        PDFSelection *selection = [PDFSelection selectionWithSpecifier:dP onPage:page];
        page = last ? [selection safeLastPage] : [selection safeFirstPage];
        if (page)
            idx = last ? [selection safeIndexOfLastCharacterOnPage:page] : [selection safeIndexOfFirstCharacterOnPage:page];
    }
    
    return [NSNumber numberWithInteger:idx == NSNotFound ? 0 : (NSInteger)idx + 1];
}

@end
