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

#import "IncomingCallAlert.h"
#import "ActiveCallViewController.h"
#import "SDKManager.h"
#import "AppDelegate.h"

@implementation IncomingCallAlert

- (void)ShowIncomingCallAlert:(NSNotification *)notification {
    
    NSLog(@"%s Received Incoming call notification", __PRETTY_FUNCTION__);
    
    [self setIncomingCallDetails];
    
    // Populate calling party name and number for incoming call alert
    NSString *callDetails = @"Unknown";
    if (self.incomingCall.callerIdentityPrivate) {
        
        callDetails = [NSString stringWithFormat:@"Restricted\n%@", self.incomingCall.remoteNumber];
    } else if (self.incomingCall.isConference) {
        
        callDetails = [NSString stringWithFormat:@"Conerence\n%@", self.incomingCall.remoteNumber];
    } else {
        
        callDetails = [NSString stringWithFormat:@"%@\n%@", self.incomingCall.remoteDisplayName, self.incomingCall.remoteNumber];
    }
    
    //Set up title and diplayMsg for incoming call alert window
    self.incomingCallAlert = [[NSAlert alloc] init];
    self.incomingCallAlert.messageText = @"Incoming Call";
    self.incomingCallAlert.informativeText = callDetails;
    [self.incomingCallAlert addButtonWithTitle:@"Accept"];
    [self.incomingCallAlert addButtonWithTitle:@"Ignore"];
    
    self.incomingCallAlert.alertStyle = NSWarningAlertStyle;
    
    // Display Alert on current window
    [self.incomingCallAlert beginSheetModalForWindow:[NSApplication sharedApplication].windows[[NSApplication sharedApplication].windows.count - 2] completionHandler:^(NSModalResponse returnCode) {
        
        // NSAlertFirstButtonReturn = Accepts the call
        // NSAlertSecondButtonReturn = Ignores the call
        if (returnCode == NSAlertFirstButtonReturn) {
            
            NSLog(@"Incoming call will be accepted");
            
            if (self.incomingCall.incomingVideoStatus == CSNetworkVideoSupported) {
                
                [self.incomingCall setVideoMode:CSVideoModeSendReceive completionHandler:^(NSError *error) {
                    
                    if (error) {
                        
                        NSLog(@"%s Error while setting video for call (%@). Error[%ld] - %@", __PRETTY_FUNCTION__, self.incomingCall, (long)error.code, error.localizedDescription);
                    } else {
                        
                        NSLog(@"%s Successfully set video for call (%@)", __PRETTY_FUNCTION__, self.incomingCall);
                    }
                }];
            }
            
            [self.incomingCall accept];
            
            // Get currently displayed NSViewController
            NSViewController *currentViewController = [NSApplication sharedApplication].mainWindow.contentViewController;
            
            for (NSViewController* controller in currentViewController.presentedViewControllers) {
                
                if (controller.isViewLoaded && controller.view.window) {
                    
                    currentViewController = controller;
                    break;
                }
            }
            
            //Get Main storyBoard
            NSStoryboard *storyBoard = [NSStoryboard storyboardWithName:@"Main" bundle:nil];
            
            //Instantiate Active Call View Controller using storyBoard
            ActiveCallViewController *activeCallView = [storyBoard instantiateControllerWithIdentifier:@"activeCallWindow"];
            //Set Incoming Call as current active call
            activeCallView.currentCall = self.incomingCall;
            
            // Push ActiveCallViewController on top of current NSViewController
            [currentViewController presentViewControllerAsSheet:activeCallView];
        } else if (returnCode == NSAlertSecondButtonReturn) {
            
            NSLog(@"Incoming call will be ignored");
            [self.incomingCall ignore];
        }
    }];
}

//Sets incoming Call
- (void)setIncomingCallDetails {
    
    CSCallService *callService = nil;
    for (CSUser *user in [SDKManager getInstance].users) {
        
        if (user.callService) {
            
            callService = user.callService;
            break;
        }
    }
    
    for (CSCall *call in callService.calls) {
        
        if (call.state == CSCallStateAlerting) {
            
            self.incomingCall = call;
            break;
        }
    }
    NSLog(@"%s Incoming call from Name:[%@], number:[%@], callType: [%@]", __PRETTY_FUNCTION__, self.incomingCall.remoteDisplayName, self.incomingCall.remoteNumber, (self.incomingCall.incomingVideoStatus == CSNetworkVideoSupported ? @"Video" : @"Audio"));
}

//  Dismiss Alert View controller in case call terminated from remote end while in ringing state
- (void)didReceiveMissedCall:(NSNotification *)notification {
    
    NSLog(@"Recieved Missed Call Notification");
    // Dismiss Alert from current window
    [[NSApplication sharedApplication].windows[[NSApplication sharedApplication].windows.count - 2] endSheet:self.incomingCallAlert.window];
}

@end

