#import "AqCoreController.h"
#import "AqBrowseHostToolbarView.h"
#import "AqDrawerController.h"
#import "AqQueryController.h"
#import "AqURLHandler.h"
#import "NSUserDefaultsExtensions.h"


@implementation AqURLHandler

    + (id) localBrowseURL; {
        return [AqURLHandler browseURLForAddress: [AqURLHandler localAddress]];
    }

    + (id) localAddress; {
        return [NSString stringWithFormat: @"%@:%i", [[NSHost currentHost] address], [defaults integerForKey: @"port"]];
    }
    
    + (id) browseURLForAddress: (id) theAddress; {
        return [NSString stringWithFormat: @"acquisition://%@/", theAddress];
    }
    
    + (void) handleAcqlURL: (NSString*) url; {
        id splitURL = [url componentsSeparatedByString: @"?"];
        id keyword = [splitURL objectAtIndex: 0];
        id query = [splitURL objectAtIndex: 1];
        query = (NSString*)CFURLCreateStringByReplacingPercentEscapes(kCFAllocatorDefault, (CFStringRef)query, CFSTR(""));
        NSLog(@"keyword:%@ query:%@", keyword, query);
        //query = [query replaceOccurrencesOfString:@"+" withString:@" " options:NSLiteralSearch range:NSMakeRange(0, [query length])];
        if ([keyword isEqual: @"query"]) {
            [[AqDrawerController instance] textQuery: query];
        }
    }

    + (id) cleansedURL: (NSString*) url; {
        while ([url hasPrefix: @"/"])
            url = [url substringFromIndex: 1]; 
        while ([url hasSuffix: @"/"])
            url = [url substringToIndex: [url length]-1];
        
        return url;
    }
    
    + (void) handleURLEvent: (id) sender; {
        NS_DURING
            id url = [[sender paramDescriptorForKeyword: keyDirectObject] stringValue];
            [AqURLHandler handleURLStringAndDisplay: url];
        NS_HANDLER
            NSLog(@"handleURLEvent exception: %@", localException);
        NS_ENDHANDLER
    }

    + (id) handleURLString: (id) url; {
        if ([url hasPrefix: @"magnet:"]) {
            [AqCoreController writeString: [NSString stringWithFormat: @"handleMagnet|%@\n", url]];
        }
        
        if ([url hasPrefix: @"acquisition:"]) {
            url = [url substringFromIndex: 12];
            url = [AqURLHandler cleansedURL: url];
            if (![url isEqual: [AqURLHandler localAddress]])
                return [AqBrowseHostToolbarView browseHost: url];
        }
        
        if ([url hasPrefix: @"acql:"]) {
            url = [url substringFromIndex: 5];
            url = [AqURLHandler cleansedURL: url];
                return [AqURLHandler handleAcqlURL: url];
        }
        
        return nil;
    }

    + (void) handleURLStringAndDisplay: (id) url; {
        id queryToDisplay = [AqURLHandler handleURLString: url];
        int index = [AqQC indexOfQuery: queryToDisplay];
        if (index > -1) [[AqDrawerController instance]->queryView selectRow: index byExtendingSelection: NO];
    }


@end