/* 
 * BundleController.m created by phr on 2001-01-13 14:42:31 +0000
 *
 * Project GSBench
 *
 * Created with ProjectCenter - http://www.projectcenter.ch
 *
 * $Id: BundleController.m,v 1.1.1.1 2001/01/13 20:48:30 robert Exp $
 */

#import "BundleController.h"
#import "Benchmarking.h"

NSString *BundleControllerLoadingException = @"BundleControllerLoadingException";

@implementation BundleController

- (id)init
{
  if ((self = [super init])) {
    NSString *bpath;
    NSDictionary *env = [[NSProcessInfo processInfo] environment];
    NSString *prefix = [env objectForKey:@"GNUSTEP_LOCAL_ROOT"];

    bpath = [[NSBundle mainBundle] pathForResource:@"Bundles" ofType:@"plist"];
    bundlesToLoad = [[NSDictionary dictionaryWithContentsOfFile:bpath] retain];

    if (!bundlesToLoad) {
      [NSException raise:BundleControllerLoadingException 
		   format:@"Bundles.plist is missing!"];
      return;
    }

     loadedBundles = [[NSMutableArray alloc] initWithCapacity:[bundlesToLoad count]];

    if (prefix && ![prefix isEqualToString:@""]) {
      bundlePath =[[prefix stringByAppendingPathComponent:@"Library/Bundles/"] copy];
    }
    else {
      bundlePath = [[NSString stringWithString:@"/usr/GNUstep/Local/Library/Bundles/"] copy];
    }
  }
  return self;
}

- (void)dealloc
{
  RELEASE(bundlePath);
  RELEASE(bundlesToLoad);
  RELEASE(loadedBundles);

  [super dealloc];
}

- (void)loadBundles
{
  NSEnumerator *enumerator;
  NSString *bundleName = nil;

  NSLog(@"loading bundles from %@...",bundlePath);

  enumerator = [bundlesToLoad keyEnumerator];
  while ((bundleName = [enumerator nextObject])) {
    NSString *s;
    NSBundle *b;

    s = [bundlePath stringByAppendingPathComponent:bundleName];

    if ([[NSFileManager defaultManager] isReadableFileAtPath:s]) {
      if ((b = [NSBundle bundleWithPath:s])) {
	[self registerBundle:b];
      }
    }
    else {
      NSLog(@"Cannot find %@ - aborting!",s);
    }
  }

  NSLog(@"bundles loaded!");
}

- (void)registerBundle:(NSBundle *)bundle
{
  Class principalClass;
 
  principalClass = [bundle principalClass];
  if ([principalClass conformsToProtocol:@protocol(Benchmarking)]) {
    id c = [[principalClass alloc] init];
    id m = [[[NSApp mainMenu] itemWithTitle:@"Benchmarks"] submenu];

    [m addItemWithTitle:[c menuItemTitle] 
       action:@selector(prepareForBenchmarking:)
       keyEquivalent:@""];
    [[m itemWithTitle:[c menuItemTitle]] setTarget:c];

    [loadedBundles addObject:c];
    RELEASE(c);
  } 
  else {
    NSLog(@"%@ is not a valid GSBench bundle controller - aborting!",NSStringFromClass(principalClass));
  }
}

@end
