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

#import "CallServiceSettingsViewController.h"
#import "ConfigData.h"
#import "SDKManager.h"

@interface CallServiceSettingsViewController ()

@end



@implementation CallServiceSettingsViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    ConfigData *configuration = [ConfigData getInstance];
    
    // Change window background to white
    self.view.wantsLayer = YES;
    self.view.layer.backgroundColor = [NSColor whiteColor].CGColor;
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(startRegistration:) name:kStartSIPLoginNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(transportChanged:) name:kSIPTransportChangedNotification object:nil];
    
    self.sipProxyAddress.stringValue = configuration.sipProxyAddress;
    self.sipProxyPort.integerValue = (UInt)configuration.sipProxyPort;
    self.sipDomain.stringValue = configuration.sipDomain;
    self.sipTransportType.state = ([configuration.sipTransport compare:@"TLS"] == NSOrderedSame) ? NSOnState : NSOffState;
    self.sipTransportType.title = ([configuration.sipTransport compare:@"TLS"] == NSOrderedSame) ? @"ON" : @"OFF";
    self.sipUsername.stringValue = configuration.sipUsername;
    self.sipPassword.stringValue = configuration.sipPassword;
    
    if (configuration.sipLogin == SipLoginStatusLoggedIn) {
        
        self.sipLoginStatus.stringValue = @"Logged In";
    } else if (configuration.sipLogin == SipLoginStatusLoggingIn) {
        
        self.sipLoginStatus.stringValue = @"Logging In";
    } else if (configuration.sipLogin == SipLoginStatusLoggedOut) {
        
        self.sipLoginStatus.stringValue = @"Not Logged In";
    }
    
    // Disable fields when opening this screen when user is Logging in
    if ((configuration.sipLogin == SipLoginStatusLoggingIn)) {
        
        self.sipProxyAddress.enabled = NO;
        self.sipProxyPort.editable = NO;
        self.sipProxyPort.enabled = NO;
        self.sipTransportType.enabled = NO;
        self.sipDomain.enabled = NO;
        
        self.sipUsername.enabled = NO;
        self.sipPassword.enabled = NO;
        
        self.sipLoginStatus.stringValue = @"Logging In";
    }
    
    NSColor *color = [NSColor blueColor];
    NSMutableAttributedString *formattedTitleApplyBtn = [[NSMutableAttributedString alloc] initWithAttributedString:self.applySettingsBtnLabel.attributedTitle];
    NSRange titleRangeApplyBtn = NSMakeRange(0, [formattedTitleApplyBtn length]);
    [formattedTitleApplyBtn addAttribute:NSForegroundColorAttributeName value:color range:titleRangeApplyBtn];
    self.applySettingsBtnLabel.attributedTitle = formattedTitleApplyBtn;
    
    NSMutableAttributedString *formattedTitleBackBtn = [[NSMutableAttributedString alloc] initWithAttributedString:self.backBtnLabel.attributedTitle];
    NSRange titleRangeBackBtn = NSMakeRange(0, [formattedTitleBackBtn length]);
    [formattedTitleBackBtn addAttribute:NSForegroundColorAttributeName value:color range:titleRangeBackBtn];
    self.backBtnLabel.attributedTitle = formattedTitleBackBtn;
}

- (void)dealloc {
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:kStartSIPLoginNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:kSIPTransportChangedNotification object:nil];
}

- (IBAction)applySettingsBtn:(id)sender {
    
    ConfigData *configuration = [ConfigData getInstance];
    
    // Check if client is Logged out
    if (configuration.sipLogin == SipLoginStatusLoggedOut) {
        
        NSLog(@"%s start user login", __PRETTY_FUNCTION__);
        
        [self saveConfiguration];
        
        self.sipLoginStatus.stringValue = @"Logging In";
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
            
            // Create user in async task
            [[SDKManager getInstance] setupClient];
        });
    } else if (configuration.sipLogin == SipLoginStatusLoggedIn) {
        
        // Check if ay configuration has changed before applying it
        if ([configuration.sipUsername isEqualToString:self.sipUsername.stringValue] &
            [configuration.sipPassword isEqualToString:self.sipPassword.stringValue] &
            [configuration.sipDomain isEqualToString:self.sipDomain.stringValue] &
            [configuration.sipProxyAddress isEqualToString:self.sipProxyAddress.stringValue] &
            (configuration.sipProxyPort == self.sipProxyPort.intValue)) {
            
            NSLog(@"%s User already logged in, do nothing", __PRETTY_FUNCTION__);
        } else {
            
            NSLog(@"%s start new user login", __PRETTY_FUNCTION__);
            
            [self saveConfiguration];
            
            self.sipLoginStatus.stringValue = @"Logging In";
            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
                
                // Create user in async task
                [[SDKManager getInstance] setupClient];
            });
        }
    } else {
        
        NSLog(@"%s User login is in progress, wait...", __PRETTY_FUNCTION__);
    }
    
    [self dismissViewController:self];
}

- (IBAction)sipTransportTypeBtn:(id)sender {
    
    ConfigData *configuration = [ConfigData getInstance];
    if (self.sipTransportType.state == NSOffState) {
        
        NSLog(@"%s set transport type to TCP", __PRETTY_FUNCTION__);
        configuration.sipTransport = @"TCP";
        configuration.sipProxyPort = 5060;
        self.sipTransportType.title = @"OFF";
        
    } else if (self.sipTransportType.state == NSOnState) {
        
        NSLog(@"%s set transport type to TLS", __PRETTY_FUNCTION__);
        configuration.sipTransport = @"TLS";
        configuration.sipProxyPort = 5061;
        self.sipTransportType.title = @"ON";
    }
    
    // Send Notification to update secreen
    [[NSNotificationCenter defaultCenter] postNotificationName:kSIPTransportChangedNotification object:nil];
}

- (IBAction)backBtn:(id)sender {
    
    // Do nothing on Back button press, just dismiss the view-controller
    [self dismissViewController:self];
}

- (void)startRegistration:(NSNotification *)notification {
    
    NSLog(@"===> user created successfully... Now start registration");
    for (CSUser *user in [SDKManager getInstance].users) {
        
        user.contactService.delegate = (id<CSContactServiceDelegate>)[SDKManager getInstance];
        [user start];
    }
}

// Called when the SIP Transport switch changes it's state.
- (void)transportChanged:(NSNotification*)aNotification {
    
    self.sipProxyPort.integerValue = [ConfigData getInstance].sipProxyPort;
}

- (void)saveConfiguration {
    
    ConfigData *configuration = [ConfigData getInstance];
    
    // Save current configuration in NSUserDefaults
    configuration.sipProxyAddress = self.sipProxyAddress.stringValue;
    configuration.sipProxyPort = self.sipProxyPort.intValue;
    configuration.sipDomain = self.sipDomain.stringValue;
    configuration.sipUsername = self.sipUsername.stringValue;
    configuration.sipPassword = self.sipPassword.stringValue;
    
    NSUserDefaults *standardUserDefaults = [NSUserDefaults standardUserDefaults];
    
    if (standardUserDefaults) {
        
        [standardUserDefaults setObject:self.sipProxyAddress.stringValue forKey:@"sipProxyAddress"];
        [standardUserDefaults setInteger:self.sipProxyPort.intValue forKey:@"sipProxyPort"];
        [standardUserDefaults setObject:self.sipDomain.stringValue forKey:@"sipDomain"];
        [standardUserDefaults setObject:self.sipUsername.stringValue forKey:@"sipUsername"];
        [standardUserDefaults setObject:self.sipPassword.stringValue forKey:@"sipPassword"];
        [standardUserDefaults synchronize];
    }
}

@end
