/*
   Project: UL

   Copyright (C) 2005 Michael Johnston & Jordi Villa-Freixa

   Author: Michael Johnston

   This application is free software; you can redistribute it and/or
   modify it under the terms of the GNU General Public
   License as published by the Free Software Foundation; either
   version 2 of the License, or (at your option) any later version.

   This application is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   Library General Public License for more details.

   You should have received a copy of the GNU General Public
   License along with this library; if not, write to the Free
   Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111 USA.
*/

#include <AppKit/AppKit.h>
#include "ULPreferences.h"

@implementation ULPreferences

- (id) initWithModelViewController: (id) object
{
	if(self = [super init])
	{
		if([NSBundle loadNibNamed: @"Preferences" owner: self] == NO)
		{
			NSWarnLog(@"Problem loading interface");
			return nil;
		}

		defaults = [NSUserDefaults standardUserDefaults];
		[[NSNotificationCenter defaultCenter] addObserver: self
			selector: @selector(updateDefaults:)
			name: NSUserDefaultsDidChangeNotification
			object: nil];
		viewController = object;

		ulDict = [NSMutableDictionary new];
		coreDict = [NSMutableDictionary new];
		[ulDict setObject: ulPDBDirectory forKey:@"PDBDirectory"];
		//\note theme is included here while no system wide GNUstep prefs application	
		//is available by default
		[ulDict setObject: ulTheme forKey:@"GSAppKitUserBundles"];
		[ulDict setObject: ulDebugLevels forKey:@"DebugLevels"];
		[coreDict setObject: coreDebugLevels forKey:@"DebugLevels"];
		[coreDict setObject: coreTraceMemory forKey:@"TraceMemory"];
		[coreDict setObject: coreOutputMemoryStatistics forKey:@"OutputMemoryStatistics"];
		[coreDict setObject: coreRedirectOutput forKey:@"RedirectOutput"];
		
		[self updateDefaults: nil];
	}

	return self;
}

- (void) dealloc
{
	[super dealloc];
}

- (void) showPreferences: (id) sender
{
	[preferencesWindow makeKeyAndOrderFront: self];
}

- (void) _setButton: (id) button forDefault: (NSString*) string inDomain: (NSDictionary*) domain
{
	if([[domain objectForKey: string] boolValue])
		[button setState: NSOnState];
	else
		[button setState: NSOffState];
}

- (void) updateDefaults: (id) sender
{
	id coreDomain, globalDomain;
	
	globalDomain = [defaults persistentDomainForName: @"NSGlobalDomain"];
	coreDomain = [defaults persistentDomainForName: @"AdunCore"];

	[ulPDBDirectory setStringValue: [defaults objectForKey: @"PDBDirectory"]];
	[ulDebugLevels setStringValue: [[defaults arrayForKey: @"DebugLevels"] componentsJoinedByString: @", "]];
	[coreDebugLevels setStringValue: [[coreDomain objectForKey: @"DebugLevels"] componentsJoinedByString: @", "]];
	[ulTheme setStringValue: [[globalDomain objectForKey: @"GSAppKitUserBundles"] componentsJoinedByString: @", "]];

	[self _setButton: coreTraceMemory
		 forDefault: @"TraceMemory"
		 inDomain: coreDomain];	
	[self _setButton: coreRedirectOutput 
		forDefault: @"RedirectOutput" 
		inDomain: coreDomain];	
	[self _setButton: coreOutputMemoryStatistics
		forDefault: @"OutputMemoryStatistics" 
		inDomain: coreDomain];	
}

- (NSArray*) _convertStringToArray: (NSString*) string
{
	id array, value, processedArray;
	NSEnumerator* valueEnum;

	array = [string componentsSeparatedByString: @","];
	if([array count] == 1)
	{
		//check if the values are separated by whitespace
		array = [string componentsSeparatedByString: @" "];
	}		

	processedArray = [NSMutableArray arrayWithCapacity: 1];
	valueEnum = [array objectEnumerator];
	while(value = [valueEnum nextObject])
		[processedArray addObject: [value stringByTrimmingCharactersInSet: 
			[NSCharacterSet whitespaceCharacterSet]]];

	return processedArray;
}

- (void) setDefault: (id) sender
{
	NSString* defaultName, *domainName;
	id coreDomain, defaultValue, globalDomain;

	coreDomain = [[defaults persistentDomainForName: @"AdunCore"] mutableCopy];
	globalDomain = [[defaults persistentDomainForName: @"NSGlobalDomain"] mutableCopy];

	if((defaultName = [[ulDict allKeysForObject: sender] objectAtIndex: 0]) != nil)
		domainName = @"UL";
	else if((defaultName = [[coreDict allKeysForObject: sender] objectAtIndex: 0]) != nil)
		domainName = @"AdunCore";
	else
		[NSException raise: NSInternalInconsistencyException
			format: @"Unknown preferences input object"];
		
	//process the senders value

	if([defaultName isEqual: @"DebugLevels"])
		defaultValue = [self _convertStringToArray: [sender stringValue]];
	else if([defaultName isEqual: @"GSAppKitUserBundles"])
		defaultValue = [self _convertStringToArray: [sender stringValue]];
	else if([sender isKindOfClass: [NSButton class]])
	{
		if([sender state] == NSOnState)
			defaultValue = [NSNumber numberWithBool: YES];
		else	
			defaultValue = [NSNumber numberWithBool: NO];
	}
	else
		defaultValue = [sender stringValue];
	
	if([defaultName isEqual: @"GSAppKitUserBundles"])
	{
		[globalDomain setObject: defaultValue forKey: defaultName];
		[defaults setPersistentDomain: globalDomain forName: @"NSGlobalDomain"];
	}
	else if([domainName isEqual: @"UL"])
	{
		[defaults setObject: defaultValue forKey: defaultName];
	}
	else
	{
		[coreDomain setObject: defaultValue forKey: defaultName];
		[defaults setPersistentDomain: coreDomain forName: @"AdunCore"];
	}

	[defaults synchronize];
}


@end
