/******************************************************************************/
/*                                                                            */
/* Copyright Avaya LLC.                                                       */
/*                                                                            */
/******************************************************************************/

#import "MessagingServiceSettingsViewController.h"
#import "SDKManager.h"
#import "ConfigData.h"

@interface MessagingServiceSettingsViewController ()

@end

@implementation MessagingServiceSettingsViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    ConfigData *configuration = [ConfigData getInstance];
    
    // Change window background to white
    self.view.wantsLayer = YES;
    self.view.layer.backgroundColor = [NSColor whiteColor].CGColor;
    
    NSColor *color = [NSColor blueColor];
    NSMutableAttributedString *formattedTitle = [[NSMutableAttributedString alloc] initWithAttributedString:self.backBtnLabel.attributedTitle];
    NSRange titleRange = NSMakeRange(0,formattedTitle.length);
    [formattedTitle addAttribute:NSForegroundColorAttributeName value:color range:titleRange];
    self.backBtnLabel.attributedTitle = formattedTitle;
    
    formattedTitle = [[NSMutableAttributedString alloc] initWithAttributedString:self.applyBtnLabel.attributedTitle];
    titleRange = NSMakeRange(0,formattedTitle.length);
    [formattedTitle addAttribute:NSForegroundColorAttributeName value:color range:titleRange];
    self.applyBtnLabel.attributedTitle = formattedTitle;
    
    self.messagingServerAddress.stringValue = configuration.messagingServerAddress;
    self.messagingPort.integerValue = (UInt)configuration.messagingPort;
    
    self.messagingUsername.stringValue = configuration.messagingUsername;
    self.messagingPassword.stringValue = configuration.messagingPassword;
    
    NSString *interval = @"";
    
    switch (configuration.messagingRefreshInterval) {
            
        default:
        case CSMessagingRefreshModePush:
            interval = @"0 (Push)";
            break;
        case CSMessagingRefreshMode1Minute:
            interval = @"1";
            break;
        case CSMessagingRefreshMode2Minutes:
            interval = @"2";
            break;
        case CSMessagingRefreshMode5Minutes:
            interval = @"5";
            break;
        case CSMessagingRefreshMode15Minutes:
            interval = @"15";
            break;
        case CSMessagingRefreshMode60Minutes:
            interval = @"60";
            break;
        case CSMessagingRefreshModeManual:
            interval = @"Manual";
            break;
    }
    self.messagingPollingInterval.title = interval;
    
    self.messagingConnectionTypeLabel.title = configuration.messagingConnectionTypeSecure ? @"YES" : @"NO";
    
    if (configuration.messagingLogin == MessagingLoginStatusLoggedIn) {
        
        self.messagingLoginStatusLabel.stringValue = @"Logged In";
    } else if (configuration.messagingLogin == MessagingLoginStatusLoggingIn) {
        
        self.messagingLoginStatusLabel.stringValue = @"Logging In";
    } else if (configuration.messagingLogin == MessagingLoginStatusLoggedOut) {
        
        self.messagingLoginStatusLabel.stringValue = @"Not Logged In";
    }
}

- (IBAction)backBtn:(id)sender {
    
    [self dismissController:self];
}

- (IBAction)applyBtn:(id)sender {
    
    ConfigData *configuration = [ConfigData getInstance];
    
    // Check if client is already logged in
    if (configuration.messagingLogin == MessagingLoginStatusLoggedOut) {
        
        NSLog(@"%s start messaging login", __PRETTY_FUNCTION__);
        
        // Save current configuration in NSUserDefaults
        configuration.messagingServerAddress = self.messagingServerAddress.stringValue;
        configuration.messagingPort = self.messagingPort.intValue;
        configuration.messagingRefreshInterval = [self parseMessagingRefreshInterval:self.messagingPollingInterval.title];
        configuration.messagingUsername = self.messagingUsername.stringValue;
        configuration.messagingPassword = self.messagingPassword.stringValue;
        configuration.messagingConnectionTypeSecure = self.messagingConnectionTypeLabel.state;
        
        NSUserDefaults *standardUserDefaults = [NSUserDefaults standardUserDefaults];
        
        if (standardUserDefaults) {
            
            [standardUserDefaults setObject:self.messagingServerAddress.stringValue forKey:@"messagingServerAddress"];
            [standardUserDefaults setInteger:self.messagingPort.intValue forKey:@"messagingPort"];
            [standardUserDefaults setInteger:[self parseMessagingRefreshInterval:self.messagingPollingInterval.title] forKey:@"messagingRefreshInterval"];
            [standardUserDefaults setObject:self.messagingUsername.stringValue forKey:@"messagingUsername"];
            [standardUserDefaults setObject:self.messagingPassword.stringValue forKey:@"messagingPassword"];
            [standardUserDefaults setBool:configuration.messagingConnectionTypeSecure forKey:@"messagingConnectionTypeSecure"];
            [standardUserDefaults synchronize];
        }
        
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
            
            self.messagingLoginStatusLabel.stringValue = @"Logging In";
            // Create user in async task
            [[SDKManager getInstance] setupClient];
        });
    } else if (configuration.messagingLogin == MessagingLoginStatusLoggedIn) {
        
        // Check if ay configuration has changed before applying it
        if ([configuration.messagingUsername isEqualToString:self.messagingUsername.stringValue] &
            [configuration.messagingPassword isEqualToString:self.messagingPassword.stringValue] &
            [configuration.messagingServerAddress isEqualToString:self.messagingServerAddress.stringValue] &
            (configuration.messagingPort == self.messagingPort.intValue) &
            (configuration.messagingRefreshInterval == [self parseMessagingRefreshInterval:self.messagingPollingInterval.title]) &
            (configuration.messagingConnectionTypeSecure == self.messagingConnectionTypeLabel.state)) {
            
            NSLog(@"%s Messaging already logged in, do nothing", __PRETTY_FUNCTION__);
        } else {
            
            NSLog(@"%s start new account login for messaging", __PRETTY_FUNCTION__);
            
            // Save current configuration in NSUserDefaults
            configuration.messagingServerAddress = self.messagingServerAddress.stringValue;
            configuration.messagingPort = self.messagingPort.intValue;
            configuration.messagingRefreshInterval = [self parseMessagingRefreshInterval:self.messagingPollingInterval.title];
            configuration.messagingUsername = self.messagingUsername.stringValue;
            configuration.messagingPassword = self.messagingPassword.stringValue;
            configuration.messagingConnectionTypeSecure = self.messagingConnectionTypeLabel.state;
            
            NSUserDefaults *standardUserDefaults = [NSUserDefaults standardUserDefaults];
            
            if (standardUserDefaults) {
                [standardUserDefaults setObject:self.messagingServerAddress.stringValue forKey:@"messagingServerAddress"];
                [standardUserDefaults setInteger:self.messagingPort.intValue forKey:@"messagingPort"];
                [standardUserDefaults setInteger:[self parseMessagingRefreshInterval:self.messagingPollingInterval.title] forKey:@"messagingRefreshInterval"];
                [standardUserDefaults setObject:self.messagingUsername.stringValue forKey:@"messagingUsername"];
                [standardUserDefaults setObject:self.messagingPassword.stringValue forKey:@"messagingPassword"];
                [standardUserDefaults setBool:configuration.messagingConnectionTypeSecure forKey:@"messagingConnectionTypeSecure"];
                [standardUserDefaults synchronize];
            }
            
            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
                
                self.messagingLoginStatusLabel.stringValue = @"Logging In";
                // Create user in async task
                [[SDKManager getInstance] setupClient];
            });
        }
    } else {
        
        NSLog(@"%s User login is in progress, wait...", __PRETTY_FUNCTION__);
    }
    
    [self dismissViewController:self];
}

- (IBAction)messagingConnectionTypeBtn:(id)sender {
    
    NSLog(@"%s state=[%ld]", __PRETTY_FUNCTION__, (long)self.messagingConnectionTypeLabel.state);
    if (self.messagingConnectionTypeLabel.state == NSOffState) {
        
        NSLog(@"%s set messaging connection type to un-secure", __PRETTY_FUNCTION__);
        self.messagingConnectionTypeLabel.title = @"NO";
        
    } else if (self.messagingConnectionTypeLabel.state == NSOnState) {
        
        NSLog(@"%s set messaging connection type to secure", __PRETTY_FUNCTION__);
        self.messagingConnectionTypeLabel.title = @"YES";
    }
}

- (int)parseMessagingRefreshInterval:(NSString *) parseInterval {
    
    int refreshInterval = CSMessagingRefreshModePush;
    
    if ([parseInterval isEqualToString:@"0 (Push)"]) {
        
        refreshInterval = CSMessagingRefreshModePush;
    } else if ([parseInterval isEqualToString:@"1"]) {
        
        refreshInterval = CSMessagingRefreshMode1Minute;
    } else if ([parseInterval isEqualToString:@"2"]) {
        
        refreshInterval = CSMessagingRefreshMode2Minutes;
    } else if ([parseInterval isEqualToString:@"5"]) {
        
        refreshInterval = CSMessagingRefreshMode5Minutes;
    } else if ([parseInterval isEqualToString:@"15"]) {
        
        refreshInterval = CSMessagingRefreshMode15Minutes;
    } else if ([parseInterval isEqualToString:@"60"]) {
        
        refreshInterval = CSMessagingRefreshMode60Minutes;
    } else if ([parseInterval isEqualToString:@"Manual"]) {
        
        refreshInterval = CSMessagingRefreshModeManual;
    }
    
    return refreshInterval;
}

@end
