#import "PreferencesController.h"
#import "ColumnListEditor.h"
#import "Config.h"

@implementation PreferencesController

- init
{
    return [super initWithWindowNibName:@"Preferences"];
}

- (void) awakeFromNib
{
    NSLog (@"Preferences : loading config");
    
    // when we start up load the data from the user defaults
    // database
    NSLog (@"Preferences: loading settings");

    [_campaignListEditor setListData:ColumnSet (kCAMPAIGNCHARSET)];
    [_combatListEditor setListData:ColumnSet (kCOMBATSET)];
    
    [_automaticAttackRolls setIntValue:Flag (kAUTOROLLATTACKS)];

    NSLog (@"Preferences: settings loaded");
}

static void CommitData(ColumnListEditor *editor, NSString *str) 
{
    // don't bother to use an Action b/c this cannot be undone anyhow
    // since it is only committed when the pref window is closed:
    NSArray *arr = [editor stringArray];
    UpdateColumnSet (str, arr);
}

// when the window is closing, save the current settings
- (void) windowWillClose:(id)sender
{
    NSLog (@"Preferences: saving settings");
    CommitData (_campaignListEditor, kCAMPAIGNCHARSET);
    CommitData (_combatListEditor, kCOMBATSET);
    UpdateFlag (kAUTOROLLATTACKS, [_automaticAttackRolls intValue]);
    
    [NotificationCenter() postNotificationName:kCONFIGCHANGED
                                        object:self];

    NSLog (@"Preferences: settings saved");
}

@end
