#import "PreferencesController.h"

static NSString* forceServerPortKey = @"forceServerPort";
static NSString* serverPortKey = @"serverPort";
static NSString* secureServerPortKey = @"secureServerPort";
static NSString* allowedUsersKey = @"allowedUsers";
static NSString* useAltNumberingKey = @"useAltNumbering";

@implementation PreferencesController

- (void)dealloc {
    [_allowedUsers release];
}

- (void)displayError:(NSString*)msg {
    NSBeginAlertSheet(@"Please verify your entry", nil, nil, nil, preferencesWindow,
                      nil, nil, nil, nil, msg);
}

- (IBAction)forceServerPort:(id)sender
{
    if ([sender state] == NSOnState) {
        [serverPort setEnabled:true];
    } else {
        [serverPort validateEditing];
        [serverPort setEnabled:false];
    }
}

- (void)correctSettings {
    if (_serverPort < 1024 || _serverPort > 65535) {
        _serverPort = 8001;
    }
    if (_secureServerPort < 1 || _secureServerPort > 65535) {
        _secureServerPort = 443;
    }
    if (_forceServerPort && _serverPort == _secureServerPort) {
        _forceServerPort = FALSE;
    }
}

- (void)initPreferences
{
    NSUserDefaults *def = [NSUserDefaults standardUserDefaults];
    _useAltNumbering = [def boolForKey:useAltNumberingKey];
    _forceServerPort = [def boolForKey:forceServerPortKey];
    _serverPort = [def integerForKey:serverPortKey];
    _secureServerPort = [def integerForKey:secureServerPortKey];
    [_allowedUsers release];
    _allowedUsers = [[def stringArrayForKey:allowedUsersKey] retain];
    [self correctSettings];
    if (_useAltNumbering) {
        [useAltNumbering setState:NSOnState];
    } else {
        [useAltNumbering setState:NSOffState];
    }
    if (_forceServerPort) {
        [forceServerPort setState:NSOnState];
        [serverPort setEnabled:TRUE];
    } else {
        [forceServerPort setState:NSOffState];
        [serverPort setEnabled:FALSE];
    }
    [serverPort setIntValue:_serverPort];
    [secureServerPort setIntValue:_secureServerPort];
    //[users setDelegate:self];
    [usersDataSource setAllowedUsers:_allowedUsers];
    [usersDataSource _allUsersCacheForcingRebuild:TRUE];
    [users reloadData];
    [usersDataSource cleanAllowedUsers];
    [def setObject:[[usersDataSource allowedUsersCopy] autorelease] forKey:allowedUsersKey];
    [_allowedUsers release];
    _allowedUsers = [[def stringArrayForKey:allowedUsersKey] retain];
}

- (BOOL)validatePreferences:(int)currentServerPort {
    BOOL useAltNumberingBool = ([useAltNumbering state] == NSOnState);
    BOOL forceServerPortBool = ([forceServerPort state] == NSOnState);
    int serverPortInt = [serverPort intValue];
    int secureServerPortInt = [secureServerPort intValue];
    if (secureServerPortInt < 1 || secureServerPortInt > 65535) {
        [self displayError:@"The secure server port must be a positive number up to 65535."];
        return FALSE;
    }
    if (forceServerPortBool) {
        if (serverPortInt < 1024 || serverPortInt > 65535) {
            [self displayError:@"The server port must be a positive number between 1024 and 65535."];
            return FALSE;
        }
        if (serverPortInt == secureServerPortInt) {
            [self displayError:@"Please specify different ports for the server and the secure server."];
            return FALSE;
        }
        if (secureServerPortInt == currentServerPort) {
            [self displayError:@"The main server is currently running on the port you specified as the secure server port. Please specify a different port for the secure server."];
            return FALSE;
        }
    } else if (serverPortInt < 1024 || serverPortInt > 65535) {
        // for invalid values: store the previous value
        // in the preferences
        serverPortInt = _serverPort;
    }
    _useAltNumbering = useAltNumberingBool;
    _forceServerPort = forceServerPortBool;
    _serverPort = serverPortInt;
    _secureServerPort = secureServerPortInt;
    [self correctSettings];
    
    NSUserDefaults *def = [NSUserDefaults standardUserDefaults];
    [def setBool:_useAltNumbering forKey:useAltNumberingKey];
    [def setBool:_forceServerPort forKey:forceServerPortKey];
    [def setInteger:_serverPort forKey:serverPortKey];
    [def setInteger:_secureServerPort forKey:secureServerPortKey];
    [def setObject:[[usersDataSource allowedUsersCopy] autorelease] forKey:allowedUsersKey];
    [self initPreferences];
    return TRUE;
}

- (void)cancelChanges {
    [serverPort validateEditing];
    [secureServerPort validateEditing];
    [self initPreferences];
}

//- (BOOL)tableView:(NSTableView *)aTableView shouldSelectRow:(int)rowIndex {
//    return FALSE;
//}

- (BOOL)useAltNumbering {
    return _useAltNumbering;
}

- (int)serverPort {
    return _serverPort;
}

- (int)secureServerPort {
    return _secureServerPort;
}

- (BOOL)forceServerPort {
    return _forceServerPort;
}

- (NSString*)allowedUsersString {
    NSString* retVal = @"";
    if (_allowedUsers != nil) {
        int i;
        for (i = 0; i < [_allowedUsers count]; ++i) {
            if (i == 0) {
                retVal = [_allowedUsers objectAtIndex:i];
            } else {
                retVal = [[retVal stringByAppendingString:@" "]
                          stringByAppendingString:[_allowedUsers objectAtIndex:i]];
            }
        }
    }
    return retVal;
}

- (IBAction)cancel:(id)sender {
    [self cancelChanges];
    [preferencesWindow orderOut:nil];
}

@end
