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

#import "ICeCoffEETrigger.h"
#import "ICeCoffEEShared.h"
#include <Carbon/Carbon.h>

static ICeCoffEETrigger *ICCF_sharedTrigger = nil;

@implementation ICeCoffEETrigger

+ (NSRange)rangeForEvent:(NSEvent *)anEvent onTarget:(NSView<NSTextInput> *)aTarget;
{
    unsigned characterIndex = [aTarget characterIndexForPoint:
			       [[aTarget window] convertBaseToScreen: [anEvent locationInWindow]]];
    NSRange range = [aTarget selectedRange];
    ICLog(@"ICeCoffEETrigger characterIndex %u selectedRange %@", characterIndex, NSStringFromRange(range));
    if (range.location == NSNotFound || range.length == 0 ||
	!NSLocationInRange(characterIndex, range)) {
	range.location = characterIndex;
	range.length = 0;
    }
    return range;
}

- (id)initForEvent:(NSEvent *)anEvent onTarget:(NSView<NSTextInput> *)aTarget;
{
    if ( (self = [super init]) != nil) {
	target = [aTarget retain];
	event = [anEvent retain];
	range = [[self class] rangeForEvent: anEvent onTarget: aTarget];
	// no typical definition of Command-Option-double-click, so we don't need to delay
	NSTimeInterval interval = ([anEvent modifierFlags] & NSAlternateKeyMask) ? 0 :
				    TicksToEventTime(GetDblTime());
	timer = [NSTimer scheduledTimerWithTimeInterval: interval
						 target: self
					       selector: @selector(timerFired:)
					       userInfo: nil
						repeats: NO];
    }
    return self;
}

+ (void)setTriggerForEvent:(NSEvent *)anEvent onTarget:(NSView<NSTextInput> *)aTarget;
{
    ICCF_sharedTrigger = [[self alloc] initForEvent: anEvent onTarget: aTarget];
    [ICCF_sharedTrigger release];
    ICLog(@"set %@", ICCF_sharedTrigger);
}

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

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

- (void)timerFired:(NSTimer *)aTimer;
{
    ICCF_sharedTrigger = nil;
}

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

+ (BOOL)cancel;
{
    if (ICCF_sharedTrigger == nil)
	return NO;
    
    [ICCF_sharedTrigger cancel];
    return YES;
}

- (NSString *)description;
{
    return [NSString stringWithFormat: @"<%@ on %@ for %@ %@>", [self className],
	    target, event, NSStringFromRange(range)];
}

@end
