// Copyright 1998-2000 Omni Development, Inc.  All rights reserved.
//
// This software may only be used and reproduced according to the
// terms in the file OmniSourceLicense.html, which should be
// distributed with this project and can also be found at
// http://www.omnigroup.com/DeveloperResources/OmniSourceLicense.html.

#import "OWScriptEventHandlerHolder.h"

#import <Foundation/Foundation.h>
#import <OmniBase/OmniBase.h>
#import <OmniFoundation/OmniFoundation.h>
#import <OWF/OWF.h>

RCS_ID("$Header: /Network/Source/CVS/OmniGroup/Frameworks/OmniHTML/Scripting.subproj/OWScriptEventHandlerHolder.m,v 1.4 2000/01/20 00:27:57 kc Exp $")

@implementation OWScriptEventHandlerHolder

- init
{
    self = [super init];
    eventHandlerLock = [[NSLock alloc] init];
    eventHandlers = nil;
    return self;
}

- (void)dealloc
{
    [eventHandlerLock lock];
    [eventHandlers release];
    eventHandlers = nil;
    [eventHandlerLock unlock];
    [eventHandlerLock release];
    eventHandlerLock = nil;
    [super dealloc];
}

- (BOOL)handleHTMLEvent:(OWScriptEvent *)event
{
    id <OWScriptResponder> handler = nil;
    BOOL returnValue;

    [eventHandlerLock lock];
    if (eventHandlers)
        handler = [[eventHandlers objectForKey:[OWScriptEvent nameForType:[event type]]] retain];
    [eventHandlerLock unlock];

    
    if (handler) {
        returnValue = [handler handleHTMLEvent:event];
        [handler release];
    } else {
        /* if we don't have a handler, allow the event to proceed */
        returnValue = YES;
    }

    return returnValue;  
}

- (BOOL)handleHTMLEventsInMainThread
{
    return NO; /* just a guess (TODO) */
}

- (void)setHandler:(id <OWScriptResponder>)handler forEventType:(OWScriptEventType)type;
{
    [eventHandlerLock lock];

    if (!eventHandlers)
        eventHandlers = [[NSMutableDictionary alloc] init];

    [eventHandlers setObject:handler forKey:[OWScriptEvent nameForType:type]];
    [eventHandlerLock unlock];
}

// Debugging

- (NSMutableDictionary *)debugDictionary;
{
    NSMutableDictionary *debugDictionary;

    debugDictionary = [super debugDictionary];

    if (eventHandlers)
        [debugDictionary setObject:eventHandlers forKey:@"eventHandlers"];
    [debugDictionary setObject:eventHandlerLock forKey:@"lock"];

    return debugDictionary;
}

@end
