//
//  AccountController.m
//  BathyScaphe
//
//  Updated by Tsutomu Sawada on 07/11/21.
//  Copyright 2005-2013 BathyScaphe Project. All rights reserved.
//  encoding="UTF-8"
//

#import "AccountController.h"

#import "AppDefaults.h"
#import "PreferencePanes_Prefix.h"

@implementation AccountController
- (id)initWithPreferences:(AppDefaults *)pref
{
    if (self = [super initWithPreferences:pref]) {
        x2chPasswordFilled = NO;
        be2chPasswordFilled = NO;
        p22chPasswordFilled = NO;
    }
    return self;
}

- (NSString *)mainNibName
{
	return @"AccountPreferences";
}

- (NSString *)localizedAccountKindForType:(BSKeychainAccountType)type
{
    if (type == BSKeychainAccountX2chAuth) {
        return PPLocalizedString(@"Account x2ch");
    } else if (type == BSKeychainAccountBe2chAuth) {
        return PPLocalizedString(@"Account be2ch");
    } else if (type == BSKeychainAccountP22chNetAuth) {
        return PPLocalizedString(@"Account p22ch");
    }
    return nil;
}

- (NSString *)localizedPasswordKindForType:(BSKeychainAccountType)type
{
    if (type == BSKeychainAccountX2chAuth) {
        return PPLocalizedString(@"Password x2ch");
    } else if (type == BSKeychainAccountBe2chAuth) {
        return PPLocalizedString(@"Password be2ch");
    } else if (type == BSKeychainAccountP22chNetAuth) {
        return PPLocalizedString(@"Password p22ch");
    }
    return nil;
}

- (void)updatePasswordField:(NSSecureTextField *)textField
{
    NSError *error = nil;
    NSString *password;

    password = [[self preferences] passwordForType:[textField tag] error:&error];
    if (error) {
        NSAlert *alert = [[[NSAlert alloc] init] autorelease];
        [alert setAlertStyle:NSWarningAlertStyle];
        [alert setMessageText:[NSString stringWithFormat:PPLocalizedString(@"Can't get password Message"), [self localizedPasswordKindForType:[textField tag]]]];
        [alert setInformativeText:[error localizedFailureReason]];
        [alert runModal];
    }
    [textField setStringValue:(password ?: @"")];
}

- (void)updateUIComponentsForType:(BSKeychainAccountType)type
{
    if (type == BSKeychainAccountX2chAuth) {
        [x2chAccountField setStringValue:([[self preferences] x2chUserAccount] ?: @"")];
        if (!x2chPasswordFilled) {
            [self updatePasswordField:x2chPasswordField];
            x2chPasswordFilled = YES;
        }
    } else if (type == BSKeychainAccountBe2chAuth) {
        [be2chAccountField setStringValue:([[self preferences] be2chAccountMailAddress] ?: @"")];
        if (!be2chPasswordFilled) {
            [self updatePasswordField:be2chPasswordField];
            be2chPasswordFilled = YES;
        }
    } else if (type == BSKeychainAccountP22chNetAuth) {
        [p22chAccountField setStringValue:([[self preferences] p22chUserAccount] ?: @"")];
        if (!p22chPasswordFilled) {
            [self updatePasswordField:p22chPasswordField];
            p22chPasswordFilled = YES;
        }
    }
}

- (void)updateUIComponents
{
    [self updateUIComponentsForType:BSKeychainAccountX2chAuth];
    [self updateUIComponentsForType:BSKeychainAccountBe2chAuth];
    [self updateUIComponentsForType:BSKeychainAccountP22chNetAuth];
}

- (void)setupUIComponents
{
    if (!_contentView) {
        return;
    }
    [self updateUIComponents];
}

- (IBAction)accountChanged:(id)sender
{
    BSKeychainAccountType type = [sender tag];
    NSString *currentAccount = [[self preferences] accountForType:type];
    NSString *nextAccount = [sender stringValue];
    
    BOOL inKeychain = [[self preferences] hasAccountInKeychain:type];

    if (!currentAccount) {
        if ([nextAccount length] > 0) {
            [[self preferences] setAccount:nextAccount forType:type];
        }
        return;
    }

    if ([nextAccount isEqualToString:currentAccount]) {
        return;
    } else {
        if ([nextAccount isEmpty]) {
            if (inKeychain) {
                // Are you sure you want to delete account (including password) completely?
                // if YES,
                // 1. delete password from keychain
                // 2. delete account (via AppDefaults)
                NSAlert *alert = [[[NSAlert alloc] init] autorelease];
                [alert setAlertStyle:NSCriticalAlertStyle];
                [alert setMessageText:[NSString stringWithFormat:PPLocalizedString(@"Empty Account Message"), [self localizedAccountKindForType:type]]];
                [alert setInformativeText:PPLocalizedString(@"Empty Account Info")];
                [alert addButtonWithTitle:PPLocalizedString(@"Empty Account Cancel")];
                [alert addButtonWithTitle:PPLocalizedString(@"Empty Account Delete")];
                if ([alert runModal] == NSAlertSecondButtonReturn) {
                    if ([[self preferences] setPassword:nil forType:type error:NULL]) {
                        [[self preferences] setAccount:nil forType:type];
                    }
                }
                [self updateUIComponentsForType:type];
            } else {
                [[self preferences] setAccount:nextAccount forType:type];
            }
        } else {
            if (inKeychain) {
                // 1. delete password from keychain
                // 2. set account (AppDefaults)
                // 3. add password to keychain
                NSString *currentPassword = nil;
                if (sender == x2chAccountField) {
                    currentPassword = [x2chPasswordField stringValue];
                } else if (sender == be2chAccountField) {
                    currentPassword = [be2chPasswordField stringValue];
                } else if (sender == p22chAccountField) {
                    currentPassword = [p22chPasswordField stringValue];
                }
                
                NSString *tmp = [currentPassword copy];
                if ([[self preferences] setPassword:nil forType:type error:NULL]) {
                    [[self preferences] setAccount:nextAccount forType:type];
                    [[self preferences] setPassword:tmp forType:type error:NULL];
                }
                [tmp release];
            } else {
                [[self preferences] setAccount:nextAccount forType:type];
            }
        }
    }
}

- (IBAction)passwordChanged:(id)sender
{
    BSKeychainAccountType type = [sender tag];
    
    NSError *error = nil;
    if (![[self preferences] setPassword:[sender stringValue] forType:type error:&error] && error) {
        NSAlert *alert = [NSAlert alertWithError:error];
        [alert beginSheetModalForWindow:[self window] modalDelegate:self didEndSelector:NULL contextInfo:NULL];
    }
}

- (BOOL)control:(NSControl *)control textShouldEndEditing:(NSText *)fieldEditor
{
    if (control == x2chPasswordField) {
        x2chPasswordFilled = NO;
    } else if (control == be2chPasswordField) {
        be2chPasswordFilled = NO;
    } else if (control == p22chPasswordField) {
        p22chPasswordFilled = NO;
    }
    return YES;
}
@end


@implementation AccountController(Toolbar)
- (NSString *)identifier
{
	return PPAccountSettingsIdentifier;
}

- (NSString *)helpKeyword
{
	return PPLocalizedString(@"Help_Account");
}

- (NSString *)label
{
	return PPLocalizedString(@"Account Label");
}

- (NSString *)paletteLabel
{
	return PPLocalizedString(@"Account Label");
}

- (NSString *)toolTip
{
	return PPLocalizedString(@"Account ToolTip");
}

- (NSString *)imageName
{
	return @"AccountsPreferences";
}
@end
