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

#import "HTTPCallServiceViewController.h"
#import "SDKManager.h"
#import "ActiveCallViewController.h"
#import "NotificationHelper.h"
#import "ConfigData.h"
#import "ClientCredentialProvider.h"

@interface HTTPCallServiceViewController ()

@property (nonatomic, strong) CSCall *currentCall;

@end

@implementation HTTPCallServiceViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // Change window background to white
    self.view.wantsLayer = YES;
    self.view.layer.backgroundColor = [NSColor whiteColor].CGColor;
    
    // Restore UI from saved configuration
    [self restoreConfiguration];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshMainWindow:) name:kRefreshWindowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(userDidRegister:) name:kUserDidRegisterNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(userDidFailToRegister:) name:kUserDidFailToRegisterNotification object:nil];

    NSLog(@"%s start user auto-login", __PRETTY_FUNCTION__);
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
        // Create user in async task
        [[SDKManager getInstance] setupClient];
    });
    
}

- (void) dealloc {
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:kRefreshWindowNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:kUserDidRegisterNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:kUserDidFailToRegisterNotification object:nil];
}

- (void)prepareForSegue:(NSStoryboardSegue *)segue sender:(id)sender {

    ActiveCallViewController *transferViewController = segue.destinationController;

    if ([segue.identifier isEqualToString:@"audioCallSegue"]) {
        NSLog(@"%s Perform Audio call segue", __PRETTY_FUNCTION__);
        [self createCallWithCompletionHandler:^(NSError *error) {
            if (error == nil) {
                NSLog(@"%s currentCall = [%@]", __PRETTY_FUNCTION__, self.currentCall);
                
                [self.currentCall start];
                
                transferViewController.currentCall = self.currentCall;
            } else {
                [transferViewController dismissController:self];
            }
        }];
    } else if ([segue.identifier isEqualToString:@"videoCallSegue"]) {
        NSLog(@"%s Perform Video call segue", __PRETTY_FUNCTION__);
        [self createCallWithCompletionHandler:^(NSError *error) {
            if (error == nil) {
                NSLog(@"%s currentCall = [%@]", __PRETTY_FUNCTION__, self.currentCall);
                
                [[SDKManager getInstance].mediaManager configureVideoForOutgoingCall:self.currentCall withVideoMode:CSVideoModeSendReceive];
                
                [self.currentCall start];
                
                transferViewController.currentCall = self.currentCall;
            } else {
                [transferViewController dismissController:self];
            }
        }];
    }
}

- (void)createCallWithCompletionHandler:(void(^)(NSError*))completionHandler {
    
    // Update configuration with UI data
    ConfigData *configuration = [self saveConfiguration];
    
    // Retrieve the token and other meeting details
    [self.unifiedPortalService
     requestToJoinMeetingWithConfiguration: configuration.unifiedPortalConfigData
     conferenceId: configuration.conferenceID
     userName: configuration.displayName
     presentationOnlyMode: NO
     callbackNumber: @""
     oneTimePin: @""
     completionHandler:
     ^(CSUnifiedPortalMeetingInfo *meetingInfo, NSError *error)
     {
         if(error != nil)
         {
             self.messageLabel.stringValue = [NSString stringWithFormat:@"Join failed with error: %@", [error localizedDescription]];
         }
         else
         {
             self.messageLabel.stringValue = @"";
             
             CSCallCreationInfo *callCreationInfo = [[CSCallCreationInfo alloc] init];
             callCreationInfo.callType             = CSCallTypeHttpMeetme;
             callCreationInfo.conferenceId         = configuration.conferenceID;
             callCreationInfo.conferencePasscode   = @"";
             callCreationInfo.portalToken          = meetingInfo.portalToken;
             callCreationInfo.uccpURL              = meetingInfo.uccpURL;
             callCreationInfo.serviceGatewayURL    = meetingInfo.serviceGatewayURL;
             callCreationInfo.portalURL            = configuration.portalURL;
             callCreationInfo.meetmeUserName       = configuration.displayName;
             callCreationInfo.presentationOnlyMode = NO;
             
             CSCall *call;
             call = [self.callService createCallWithInfo: callCreationInfo];
             call.remoteAddress = configuration.conferenceID;
             
             self.currentCall = call;
         }
         completionHandler(error);
     }];
}

- (IBAction)guestLoginCheckBoxClicked:(id)sender {
    BOOL isGuest = [(NSButton*)sender state] == NSOnState;
    self.conferenceUsernameTextField.enabled = !isGuest;
    self.conferencePasswordTextField.enabled = !isGuest;
    self.displayNameTextField.enabled = isGuest;
}

- (void)refreshMainWindow:(NSNotification *)notification {
    
    CSUser *user = [SDKManager getInstance].user;
    if (user) {
        
        if (user.callService) {
            self.callService = user.callService;
        }
        if (user.unifiedPortalService) {
            self.unifiedPortalService = user.unifiedPortalService;
        }
    }
    
    if (self.unifiedPortalService == nil) {
        self.makeVideoCallLabel.hidden = YES;
        self.makeAudioCallLabel.hidden = YES;
        self.messageLabel.stringValue = @"Unified Portal Service is not available";
    }
}

- (void)userDidRegister:(NSNotification *)notification {
    self.makeVideoCallLabel.hidden = NO;
    self.makeAudioCallLabel.hidden = NO;
    self.messageLabel.stringValue = @"";
}

- (void)userDidFailToRegister:(NSNotification *)notification {
    self.makeVideoCallLabel.hidden = YES;
    self.makeAudioCallLabel.hidden = YES;
    self.messageLabel.stringValue = @"Unified Portal Service is not available";
}

- (void)restoreConfiguration {
    ConfigData *configuration = [ConfigData getInstance];
    [self.guestLoginCheckBox setState:(configuration.loginAsGuest? NSOnState : NSOffState)];
    self.conferenceURLTextField.stringValue = configuration.conferenceURL;
    self.conferenceUsernameTextField.stringValue = configuration.conferenceUsername;
    self.conferenceUsernameTextField.enabled = !configuration.loginAsGuest;
    self.conferencePasswordTextField.stringValue = configuration.conferencePassword;
    self.conferencePasswordTextField.enabled = !configuration.loginAsGuest;
    self.displayNameTextField.stringValue = configuration.displayName;
    self.displayNameTextField.enabled = configuration.loginAsGuest;
}

- (ConfigData *)saveConfiguration {
    ConfigData *configuration = [ConfigData getInstance];
    configuration.conferenceURL = self.conferenceURLTextField.stringValue;
    configuration.loginAsGuest = (self.guestLoginCheckBox.state == NSOnState);
    configuration.displayName = (self.displayNameTextField.stringValue.length > 0)? self.displayNameTextField.stringValue : @"SampleConferenceAppUser";
    configuration.conferenceUsername = self.conferenceUsernameTextField.stringValue;
    configuration.conferencePassword = self.conferencePasswordTextField.stringValue;
    [configuration saveConfiguration];
    return configuration;
}

@end
