//
//  AppleScript.m
//  CyTV
//
//  Created by Andreas Junghans on 17.12.07.
//  Copyright 2007 __MyCompanyName__. All rights reserved.
//

#import "AppleScript.h"

static NSMutableDictionary *__scriptDict = nil;

@implementation AppleScript

+ (void)initialize {
    if (self == [AppleScript class]) {
        __scriptDict = [[NSMutableDictionary alloc] init];
    }
}

+ (NSAppleEventDescriptor *)executeScript:(NSString *)script {
    // try to find the script in the dictionary
    NSAppleScript *scriptObject = [__scriptDict objectForKey:script];
    NSDictionary* errorInfo;
    if (scriptObject == nil) {
        scriptObject = [[NSAppleScript alloc] initWithSource:script];
        if (![scriptObject compileAndReturnError:&errorInfo]) {
            NSException* exception = [NSException exceptionWithName:@"AppleScriptException"
                                                             reason:[NSString stringWithFormat:@"Cannot compile script: %@", script]
                                                           userInfo:errorInfo];
            [scriptObject release];
            @throw exception;
        }
        [__scriptDict setObject:scriptObject forKey:script];
    }
    NSAppleEventDescriptor *retVal = [scriptObject executeAndReturnError:&errorInfo];
    if (retVal == nil) {
        NSException* exception = [NSException exceptionWithName:@"AppleScriptException"
                                                         reason:[NSString stringWithFormat:@"Cannot execute script: %@", script]
                                                       userInfo:errorInfo];
        @throw exception;
    }
    return retVal;
}

@end
