//
//  ICeCoffEETrigger.m
//  ICeCoffEE APE
//
//  Created by Nicholas Riley on 5/14/05.
//  Copyright 2005 Nicholas Riley. All rights reserved.
//

#import "ICeCoffEETrigger.h"
#import "ICeCoffEE.h"


ICeCoffEETrigger *ICCF_sharedTrigger = nil;

@implementation ICeCoffEETrigger

- (id)initForEvent:(NSEvent *)anEvent onTarget:(NSText<NSTextInput> *)aTarget;
{
    if ( (self = [super init]) != nil) {
	target = [aTarget retain];
	event = [anEvent retain];
	characterIndex = [aTarget characterIndexForPoint: [[aTarget window] convertBaseToScreen: [anEvent locationInWindow]]];
	timer = [NSTimer scheduledTimerWithTimeInterval: TicksToEventTime(GetDblTime())
						 target: self
					       selector: @selector(timerFired:)
					       userInfo: nil
						repeats: NO];
    }
    return self;
}

+ (void)setTriggerForEvent:(NSEvent *)event onTarget:(NSText<NSTextInput> *)target;
{
    ICCF_sharedTrigger = [[self alloc] initForEvent: event onTarget: target];
    [ICCF_sharedTrigger release];
}

- (void)dealloc;
{
    timer = nil;
    [target release];
    target = nil;
    [event release];
    event = nil;
    ICLog(@"%@ dealloc", self);
    [super dealloc];
}

- (void)timerFired:(NSTimer *)timer;
{
    ICCF_sharedTrigger = nil;
    [target setSelectedRange: NSMakeRange(characterIndex, 0)];
    ICCF_LaunchURLFromTextView(target, event);
}

- (void)cancel;
{
    ICCF_sharedTrigger = nil;
    [timer invalidate]; // we get dealloced inside here, so don't do anything else
}

@end
