/*
 Babylon Service - lookup words in www.babylon.com
 Copyright © 2006 Nir Soffer

 This program is free software; you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation; either version 2 of the License, or
 (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program; if not, write to the Free Software
 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

#import "BabylonService.h"


@implementation BabylonService

#pragma mark Services

- (void)lookupSelectionService:(NSPasteboard *)pboard userData:(NSString *)data error:(NSString **)error
{
    if (! [[pboard types] containsObject:NSStringPboardType]) {
        *error = @"Error: pasteboard doesn't contain a string.";
        return;
    }

    NSString *selection = [pboard stringForType:NSStringPboardType];
    if (selection == nil) {
        *error = @"Error: coould not get selection from pastebord.";
        return;
    }

    // XXX Add a way to select the service language
    NSURL *url = [self urlForTerm:selection language:@"Hebrew"];
    
    if (![[NSWorkspace sharedWorkspace] openURL:url]) {
        *error = [NSString stringWithFormat:@"Error: could not open url: %@", url];
        return;
    }
}

#pragma mark Private

- (NSURL *)urlForTerm:(NSString *)aTerm language:(NSString *)language;
{
    // User may select whitespace by mistake
    NSString *trimmedTerm = [aTerm stringByTrimmingCharactersInSet:
        [NSCharacterSet whitespaceAndNewlineCharacterSet]];
    
    NSString *escapedTerm = [self stringByAddingPercentEscapesToPathComponent:
        trimmedTerm];
    
    NSString *path = [escapedTerm stringByAppendingPathComponent:language];
    
    NSURL *baseURL = [NSURL URLWithString:@"http://www.babylon.com/definition/"];
    
    return [NSURL URLWithString:path relativeToURL:baseURL];
}

- (NSString *)stringByAddingPercentEscapesToPathComponent:(NSString *)component
{
    // See http://rfc.net/rfc2396.html section 3.3. Path Component
    NSString *reservedPathComponentCharacters = @"/;=?";
    
    NSString *escaped = (NSString *)CFURLCreateStringByAddingPercentEscapes(
        NULL, // default allocator
        (CFStringRef)component, 
        NULL, // no unescaped characters
        (CFStringRef)reservedPathComponentCharacters, // URL characters to escape
        kCFStringEncodingUTF8);
    
    return [escaped autorelease];
}

@end
