#import "NetTalkThinker.h"
#import <appkit/appkit.h>
#import <sys/dir.h>

#define NTK_RTFD "RTFDChat"
#define EXTENSION "nettalk"

@implementation NetTalkThinker(BundleLoading)

- (List *)getBundlesForDirectory:(const char *)dirname
{
	DIR             *dir = NULL;
	struct	direct	*dr;
	const char      *ext;
	char             path[1025];
	List            *bundles;

	dir	= opendir(dirname);
	if(!dir)
		return nil;
	bundles = [[List allocFromZone:[self zone]] init];
	
	while((dr = readdir(dir))!=0)
	{
		ext = strrchr(dr->d_name, '.');
		if (ext)
			if (strcmp(ext+1, EXTENSION) == 0)
			{
				sprintf(path, "%s/%s", dirname, dr->d_name);
				fprintf(stderr, "[NetTalk: Loading %s]\n", path);
				[bundles addObjectIfAbsent:
					[[NXBundle alloc] initForDirectory:(const char *)path]];
			}
	}	
	closedir(dir);
	return bundles;
}

- processBundlesInList:(List *)list
{
	char        path[1024];
	const char *bundlename;
	char        helpname[1024];
	NXBundle   *aBundle;
	int         i;
	
	for (i = 0; i < [list count]; i++)
	{
		aBundle = [list objectAt:i];
		[bundleList addObject:aBundle];
		currentControllerClass = [aBundle principalClass];
		bundlename = [currentControllerClass name];
		sprintf(helpname, "%s%s", bundlename, "Help");
		[aBundle getPath:path forResource:helpname ofType:""];
		*strrchr(path, '/') = 0;
		[[NXHelpPanel new] addSupplement:helpname inPath:path];
	}
	
	return self;
}

/*****************************************************************/
/* - initializeBundles:sender                          (->self)  */
/*                                                               */
/*  Inititalizes the bundleList by loading bundles from          */
/*  .../NetTalk.app, ~/Library/NetTalk,                          */
/*  and /LocalLibrary/NetTalk.                                   */
/*  Sets the currentControllerClass to the first bundle's class. */
/*****************************************************************/
- initializeBundles:sender
{
	List   *list;
	char    appPath[1025];     
	char    userPath[1025];     
	
	bundleList = [[List alloc] initCount:1];
	
	strcpy(appPath, NXArgv[0]);
	*strrchr(appPath, '/') = 0;
	
	list = [self getBundlesForDirectory:appPath];
	[self processBundlesInList:list];
	[list free];
	
	sprintf(userPath, "%s/Library/NetTalk", NXHomeDirectory());
	
	list = [self getBundlesForDirectory:userPath];
	[self processBundlesInList:list];
	[list free];
	
	list = [self getBundlesForDirectory:"/LocalLibrary/NetTalk"];
	[self processBundlesInList:list];
	[list free];
		
	currentControllerClass = [[bundleList objectAt:0] principalClass];
	
	return self;
}


- (Class)controllerClassFor:(const char *)className
{
	int    i = 0;
	Class  controllerClass = nil;
	
	while (!controllerClass && (i < [bundleList count]))
	{
		if ([[bundleList objectAt:i] classNamed:className])
			controllerClass = [[bundleList objectAt:i] principalClass];
		i++;
	}
	return controllerClass;
}

@end
