
#import "AM.h"
#import "Preferences.h"
#import "Dial.h"
#import "Addresses.h"


@interface AM (PrivateAMMethods)	

- findWindowforName: (const char*)name  andClass: cass ;
- openAnAddressBook: (const char*)filename ;

@end



@implementation AM


- info: sender
{
	if (!infoPanel)
		[NXApp loadNibSection:"InfoPanel.nib" owner:self] ;
	[infoPanel orderFront: self] ;
	return  self ;	
}


- preferences: sender
{
	if (!preferencesPanel)
		preferencesPanel = [[Preferences alloc] init] ;
	[preferencesPanel orderFront: self] ;
	return  self ;	
}


- dial: sender
{
	[self newDialNumber: NULL] ;
	return  self ;	
}


- newDialNumber: (const char*)number
{
	if (!dialWindow)
		dialWindow = [[Dial alloc] init] ;
	[dialWindow newNumber: number] ;
	return  self ;	
}


static const char *const addressType[] = { "addresses", NULL } ;  

- loadAddresses: sender
{
	id					myOpenPanel ;
	char				path [MAXPATHLEN+1] ;
	
	if ((myOpenPanel = [OpenPanel new]))
	{
		sprintf (path,"%s/Library/Addresses",NXHomeDirectory()) ;
		if ([myOpenPanel runModalForDirectory: path file: NULL types: addressType] == NX_OKTAG)
			[self openAnAddressBook: [myOpenPanel filename]] ;
	}
	return  self ;
}


- (int)app:app openFile:(const char *)path type:(const char *)type
{
	if (!strcmp(type,addressType[0]))
	{
		[self openAnAddressBook: path] ;
		return  YES ;
	}
	else
	{
	    NXRunAlertPanel ("Dial","Could not open file.",NULL,NULL,NULL) ;
		return  NO ;
	}
}


- (BOOL)appAcceptsAnotherFile: sender
{
    return  YES ;
}


#define FAXSIGNAL				"/tmp/faxsignal.am"

- faxSignal: sender
{
	FILE	*fp ;

	fp = fopen (FAXSIGNAL,"w") ;
	fclose (fp) ;
	return  self ;	
}


- appDidInit: sender
{
	struct _NXDefault	ourDefaults [] = 
						{
							{ "dial_command" , "/usr/local/bin/dial" } ,
							{ "device" , "/dev/cufb" } ,
							{ NULL , NULL } ,
						} ;
	NXRegisterDefaults ([self appName],ourDefaults) ;
	return  self ;
}


- appWillTerminate: sender
{
	return self ;
}


// ------------------- private methods -------------------------

- findWindowforName: (const char*)nam  andClass: cass
{
	List		*windowlist = [NXApp windowList] ;
	Window		*window ;
	id			anObject ;
	int			ii , count = [windowlist count] ;
	
	for (ii = 0 ; ii < count ; ii++)
	{
		window = [windowlist objectAt: ii] ;
		anObject = [window delegate] ;
		if ([anObject isMemberOf: cass])
			if (!strcmp(nam,[anObject name]))
				return  anObject ;
	}
	return  nil ;	
}


- openAnAddressBook: (const char*)filename
{
	Addresses	*anAddress = [self findWindowforName: filename andClass: [Addresses class]] ;
	
	if (anAddress)
		[anAddress orderFront: self] ;
	else
		[[Addresses alloc] initForAddressBook: filename] ;
	return  self ;	
}

@end
