#import <c.h>
#import <stdlib.h>

#import <nikit/NIOpenPanel.h>

#import "NLoad.h"
#import "NLoadCommon.h"

#import "LoadView.h"
#import "RPCLoadView.h"
#import "UDPLoadView.h"

#define BORDER 3

#define PATH "/machines"
#define PROMPT "Host to monitor:"

static NXDefaultsVector myDefaults = { {"Hosts", NULL},
				       {"LocalUpdateSeconds", "10"},
				       {"RemoteUpdateSeconds", "60"},
				       {"HostsWaitSeconds", "4"},
				       {"QueueLength", "-1"},
				       {NULL} };

@implementation NLoad : Application

+ initialize
{
	NXRegisterDefaults(APPLICATION, myDefaults);
	return [super initialize];
}

- appDidInit:sender
{
	NXRect cRect, fRect;
	id icon = [sender appIcon], aView;
 	const char *string;
 	char *hostPtr, *nextHostPtr;
	
	[[panel = [NIOpenPanel new] setDirectoryPath:PATH] setListTitle:PROMPT];
	
	xLoc = yLoc = 0.0;

	[self getScreenSize:&size];

	[icon getFrame:&fRect];

	[Window getContentRect:&cRect forFrameRect:&fRect style:[icon style]];

	cRect.origin.x = cRect.origin.y = BORDER;
	cRect.size.width -= BORDER * 2;
	cRect.size.height -= BORDER * 2;

	[[icon contentView] addSubview:(aView = [[LoadView alloc] initFrame:&cRect])];

	[icon display];

	[aView startTimer];

	if ((string = getDefault("Hosts")) == NULL) return self;

	nextHostPtr = NXCopyStringBuffer(string);
 
	while (nextHostPtr != NULL) {
		hostPtr = nextHostPtr;
		if ((nextHostPtr = index(hostPtr, ';')) != NULL) *nextHostPtr++ = '\0';
		[self addHost:hostPtr];
		}

	return self;
}

- addHost:(const char *) string
{
	NXRect cRect, fRect;
	id aWindow, aView;
 	char *hostPtr, *namePtr, *sPtr, *typePtr;

	NXSetRect(&cRect, xLoc, yLoc, WIDTH, HEIGHT);
    [Window getFrameRect:&fRect forContentRect:&cRect style:NX_TITLEDSTYLE];

	aWindow = [[Window alloc] initContent:&cRect style:NX_TITLEDSTYLE
		backing:NX_BUFFERED buttonMask:NX_CLOSEBUTTONMASK defer:NO];

	namePtr = NXCopyStringBuffer(string);
	if ((sPtr = index(namePtr, '.')) != NULL) *sPtr = '\0';
	[aWindow setTitle:namePtr];
	free(namePtr);

	cRect.origin.x = cRect.origin.y = BORDER;
	cRect.size.width -= BORDER * 2;
	cRect.size.height -= BORDER * 2;

	hostPtr = NXCopyStringBuffer(string);
	if ((typePtr = rindex(hostPtr, ':')) != NULL && strcmp(typePtr, ":udp") == 0) {
		*typePtr = '\0';
		aView = [[UDPLoadView alloc] initFrame:&cRect];
		}
	else aView = [[RPCLoadView alloc] initFrame:&cRect];
	[aView setHostName:hostPtr];
	free(hostPtr);
	
	[[aWindow display] orderFront:nil];

	[[aWindow contentView] addSubview:aView];

	[[aView display] startTimer];
	
	xLoc += fRect.size.width;
	if((xLoc + fRect.size.width) > size.width) { xLoc = 0.0; yLoc += fRect.size.height; }
	
	return self;
}

- addNIHost:sender
{
	if ([panel runModal] == NX_OKTAG) [self addHost:[panel directory]];

	return self;
}

- setVersion:anObject
{
	[(version = anObject) setStringValue:VERSION];
	
	return self;
}

@end
