/*
 Flash: Flashcard program
 Copyright (C) 2005, Niko Matsakis (niko@alum.mit.edu)
 
 This program 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 program 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 General Public License for more details.
 
 You should have received a copy of the GNU General Public License
 along with this program; if not, write to the Free Software
 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */

#import "Preferences.h"
#import "OAKeyboardLayout.h"
#import "Errors.h"

#define kDialogKeyboardName @"dialogKeyboardName"
#define kMaxDays @"maxDays"

static Preferences *_Preferences;

@interface Preferences (Internal)
- (void) _registerDefaults;
@end

@implementation Preferences

- init
{
    if ((self = [super init])) {
        _defaults = [[NSUserDefaults standardUserDefaults] retain];
        
        if (_Preferences == nil) {
            // remember the first instance created: note that this is 
            // done in MainMenu.nib
            _Preferences = [self retain];
            [self _registerDefaults];
        }        
    }
    return self;
}

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

+ sharedPreferences
{
    if (!_Preferences)
        [[[Preferences alloc] init] release];
    return _Preferences;
}

- (NSArray*) allKeyboardLayouts
{
    return [OAKeyboardLayout allKeyboardLayouts];
}

- (NSString*) dialogKeyboardName
{
    return [_defaults stringForKey:kDialogKeyboardName];
}

- (void) setDialogKeyboardName:(NSString*)name
{
    [_defaults setObject:name forKey:kDialogKeyboardName];
}

- (OAKeyboardLayout*) dialogKeyboard
{
    return [OAKeyboardLayout keyboardLayoutWithName:[self dialogKeyboardName]];
}

- (int) maxDays
{
	return [_defaults integerForKey:kMaxDays];
}

- (void) setMaxDays:(int)maxDays
{
	[_defaults setInteger:maxDays forKey:kMaxDays];
}

@end

@implementation Preferences (Internal)

- (void) _registerDefaults
{
    // use as the default keyboard layout the keyboard we got when we first loaded
    // the program
    OAKeyboardLayout *keyl = [OAKeyboardLayout currentKeyboardLayout];
    NSDictionary *def = [NSDictionary dictionaryWithObjectsAndKeys:
						 [keyl name], kDialogKeyboardName,
						 [NSNumber numberWithInt:45], kMaxDays,
						 nil];
    [_defaults registerDefaults:def];
}

@end
