//
//  GrowlNotifier.m
//  Afficheur
//
//  Created by kichi on 08/04/07.
//  Copyright 2008 Katsuhiko Ichinose. All rights reserved.
//

#import "GrowlNotifier.h"
#import "HotKeyedApplication.h"


@implementation GrowlNotifier

- (GrowlNotifier *)initWithDelegate:(id)delegate
{
	_dict = nil;
	_delegate = nil;
	self = [super init];
	if (self)
	{
		_dict = [[NSMutableDictionary alloc] initWithObjectsAndKeys:
				 //[[NSProcessInfo processInfo] processIdentifier], GROWL_APP_PID,
				 nil];
		_delegate = delegate;
	}
	return self;
}

- (void)dealloc
{
	[_dict release];
	[super dealloc];
}

- (void)startWithApplicationName:(NSString *)applicationName
				   notifications:(NSArray *)notifications
			dafaultNotifications:(NSArray *)defaultNotifications
							icon:(NSImage *)icon
{
	[_dict setValue:applicationName forKey:GROWL_APP_NAME];
	[_dict setValue:notifications forKey:GROWL_NOTIFICATIONS_ALL];
	if (defaultNotifications)
	{
		[_dict setValue:defaultNotifications forKey:GROWL_NOTIFICATIONS_DEFAULT];
	}
	else
	{
		[_dict setValue:notifications forKey:GROWL_NOTIFICATIONS_DEFAULT];
	}
	NSImage* img = icon;
	if (!img)
	{
		img = [[NSApplication sharedApplication] applicationIconImage];
	}
	[_dict setValue:[img TIFFRepresentation] forKey:GROWL_APP_ICON];
    if ([GrowlApplicationBridge isGrowlInstalled])
	{
		if (![GrowlApplicationBridge isGrowlRunning])
		{
			[[NSWorkspace sharedWorkspace] launchApplication:@"GrowlHelperApp"];
		}
	}
	[GrowlApplicationBridge setGrowlDelegate:self];
}

- (void)notifyWithTitle:(NSString *)title
			description:(NSString *)description
	   notificationName:(NSString *)notificationName
			   iconData:(NSData *)iconData
			   priority:(signed int)priority
			   isSticky:(BOOL)isSticky
		   clickContext:(id)clickContext
{
	[GrowlApplicationBridge notifyWithTitle:title
								description:description
						   notificationName:notificationName
								   iconData:iconData
								   priority:priority
								   isSticky:isSticky
							   clickContext:clickContext];
}

//	Growl delegate

- (NSDictionary *)registrationDictionaryForGrowl
{
	return _dict;
}

- (NSString *)applicationNameForGrowl
{
	return [_dict valueForKey:GROWL_APP_NAME];
}

- (NSData *)applicationIconDataForGrowl
{
	return [_dict valueForKey:GROWL_APP_ICON];
}

- (void)growlIsReady
{
	if (_delegate && [_delegate respondsToSelector:@selector(growlIsReady)])
	{
		[_delegate performSelector:@selector(growlIsReady)];
	}
}

- (void)growlNotificationWasClicked:(id)clickContext
{
	if (_delegate && [_delegate respondsToSelector:@selector(growlNotificationWasClicked:)])
	{
		[_delegate performSelector:@selector(growlNotificationWasClicked:) withObject:clickContext];
	}
}

- (void)growlNotificationTimedOut:(id)clickContext
{
	if (_delegate && [_delegate respondsToSelector:@selector(growlNotificationTimedOut:)])
	{
		[_delegate performSelector:@selector(growlNotificationTimedOut:) withObject:clickContext];
	}
}

@end
