#import <appkit/appkit.h>
#import "PrefsController.h"
#import "SwitchView.h"

@implementation PrefsController

#define TRUNCATE 0
#define PROMPT 1
#define OFF 0
#define ON 1

+ initialize
{
	// make sure that self is a PrefsController
	// class before setting class initialization:
	// this prevents subclasses from performing
	// reinitialization
	if (self == [PrefsController class])
		{
		const char *appName = [NXApp appName];

		static NXDefaultsVector theDefaults =
			{
				{"Truncate", "NO"},
				{"Prompt", "NO"},
				{NULL, NULL}
			};

		NXRegisterDefaults(appName, theDefaults);
		}
	return self;
}

- awakeFromNib
{
	const char *appName = [NXApp appName];
	const char *truncateFlag;

	truncateFlag =
		NXGetDefaultValue(appName, "Truncate");
	// make sure truncateFlag is not NULL before
	// comparing it
	if (truncateFlag)
		{
		if (strcasecmp(truncateFlag, "YES") == 0)
			[truncateSwitch setState:ON];
		else
			[truncateSwitch setState:OFF];
		}
	return self;
}

- setTruncate:sender
{
	const char *appName = [NXApp appName];
	int state = [truncateSwitch state];
	if (state == OFF)
		NXWriteDefault(appName, "Truncate", "NO");
	else
		NXWriteDefault(appName, "Truncate", "YES");
	return self;
}

- (BOOL)shouldTruncate
{
	const char *truncateFlag;
	const char *appName = [NXApp appName];

	// value in database may be newer than value
	// in registration table because of Prefs
	// panel; thus, update value in table to
	// match value in database
	NXUpdateDefault(appName, "Truncate");
	// get value from registration table
	// now that it's been updated
	truncateFlag =
		NXGetDefaultValue(appName, "Truncate");
	// make sure truncateFlag is not NULL before
	// comparing it
	if (truncateFlag)
		{
		if (strcasecmp(truncateFlag, "YES") == 0)
			return YES;
		}
	return NO;
}

- displayPrefsPanel:sender
{
	if (!prefsPanel)
		{
		[NXApp loadNibSection:"Prefs.nib"
			owner:self withNames:NO];
		[switchView switchToView:truncateSwitch];
		}
	[prefsPanel makeKeyAndOrderFront:nil];
	return self;
}

- showAccessoryView:sender
{
	int index;
	id popUpList;

	// the popuplist is the button's target
	popUpList = [popUpButton target];
	// get title of selected item and
	// then get index of title in
	// popuplist
	index = [popUpList indexOfItem:
			[popUpList selectedItem]];
	switch(index)
		{
		case TRUNCATE:
			[switchView switchToView:truncateSwitch];
			break;
		case PROMPT:
			[switchView switchToView:promptSwitch];
			break;
		}
	return self;
}

@end;
