//
//  MFClickThroughDisabler.m
//
//  Copyright (c) 2003 Michel Fortin.
//
//  This program is free software; you can redistribute it and/or modify it
//  under the terms of the GNU Lesser General Public License as published by the
//  Free Software Foundation, version 2 of the License or any later version.
//
//  http://michelf.webhop.org/lgpl.html
//

#import "MFClickThroughDisabler.h"


@implementation MFClickThroughDisabler

+ (id)clickThroughDisablerWithControl:(NSControl *)aControl {
	return [[[self alloc] initWithControl:aControl] autorelease];
}

- (id)initWithControl:(NSControl *)aControl {
	self = [super init];
	[self setControl:aControl];
	return self;
}

- (NSControl *)control {
	return control;
}

- (void)setControl:(NSControl *)aControl {
	// Enable control since it is no more under the disabler influence
	[control setEnabled:YES];
	[[NSNotificationCenter defaultCenter] removeObserver:self];
	
	[aControl retain];
	[control release];
	control = aControl;
	
	if ( control != nil ) {
		// Add observer notifications for becoming and resigning main window status
		[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(windowDidBecomeMain:) name:NSWindowDidBecomeMainNotification object:[control window]];
		[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(windowDidResignMain:) name:NSWindowDidResignMainNotification object:[control window]];
		
		// Set the control to be enabled depending of the window status
		[control setEnabled:([[control window] isMainWindow])];
	}
}

- (void)_directEnable {
	[[self control] setEnabled:YES];
}

- (void)windowDidBecomeMain:(NSNotification *)notification {
	// Put it on the run loop so that it enable itself after receiving the click
	[self performSelector:@selector(_directEnable) withObject:nil afterDelay:0];

}

- (void)windowDidResignMain:(NSNotification *)notification {
	[[self control] setEnabled:NO];
}


@end
