#import "PreferencesController.h"

static NSString *SKIP_BACK_TIME_KEY = @"skipBackTime";
static NSString *SKIP_FORWARD_TIME_KEY = @"skipForwardTime";

@implementation PreferencesController

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

- (void)correctSettings {
    if (_skipBackTime < 5 || _skipBackTime > 10000) {
        _skipBackTime = 30;
    }
    if (_skipForwardTime < 5 || _skipForwardTime > 10000) {
        _skipForwardTime = 30;
    }
}

- (void)initPreferences {
    NSUserDefaults *def = [NSUserDefaults standardUserDefaults];
    _skipBackTime = [def integerForKey:SKIP_BACK_TIME_KEY];
    _skipForwardTime = [def integerForKey:SKIP_FORWARD_TIME_KEY];
    [self correctSettings];
    [skipBackTimeControl setIntValue:_skipBackTime];
    [skipForwardTimeControl setIntValue:_skipForwardTime];
}

- (BOOL)validatePreferences {
    int skipBackTime = [skipBackTimeControl intValue];
    int skipForwardTime = [skipForwardTimeControl intValue];
    if (skipBackTime < 5 || skipBackTime > 10000 ||
        skipForwardTime < 5 || skipForwardTime > 10000) {
        [self displayError:@"The skip time must be between 5 and 10000 seconds."];
        return FALSE;
    }
    _skipBackTime = skipBackTime;
    _skipForwardTime = skipForwardTime;
    [self correctSettings];

    NSUserDefaults *def = [NSUserDefaults standardUserDefaults];
    [def setInteger:_skipBackTime forKey:SKIP_BACK_TIME_KEY];
    [def setInteger:_skipForwardTime forKey:SKIP_FORWARD_TIME_KEY];
    [def synchronize];
    [self initPreferences];
    
    return TRUE;
}

- (void)cancelChanges {
    [skipBackTimeControl validateEditing];
    [skipForwardTimeControl validateEditing];
    [self initPreferences];
}

- (IBAction)ok:(id)sender {
    if ([self validatePreferences]) {
        [preferencesWindow close];
    }
}

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

- (int)skipBackTime {
    return _skipBackTime;
}

- (int)skipForwardTime {
    return _skipForwardTime;
}

@end
