/********* ApxorCordovaPlugin.m Cordova Plugin Implementation *******/

@import WebKit;

#import "ApxorCordovaPlugin.h"
#import "ApxorSDK/ApxorSDK.h"
#import "APXRTAPlugin/APXRTAPlugin.h"
#import "APXRTAPlugin/APXRTAUtilities.h"
#import "APXContextEvaluator/APXContextEvaluator.h"
#import "APXSurveyPlugin/APXSurveyPlugin.h"

@implementation ApxorCordovaPlugin

NSString *const INLINE_SHOWN = @"inline_shown";
NSString *const HANDLE_DEEPLINK = @"HandleDeeplink";

CDVInvokedUrlCommand *deeplinkCommand; //used to store the callback
/*
*   Public methods
*/

- (void)pluginInitialize {
    [[APXController sharedController] markAsCordova];
    
    //register to events
    [[APXController sharedController] registerForEventWithType:APXEventTypeApp listener:self];
    [[APXController sharedController] registerForEventWithType:APXEventTypeCENavigation listener:self];
    [[APXController sharedController] registerForEventWithType:APXEventTypeClient listener:self];
    [[APXController sharedController] registerForEventWithType:APXEventTypeInternal listener:self];

    //dummy init survey plugin
    [[APXSurveyPlugin alloc] init];

    //set tag
    [self.webView setTag:121];
    //call super
    [super pluginInitialize];
}

- (void)setUserIdentifier:(CDVInvokedUrlCommand*)command
{
    NSString* userID = [command.arguments objectAtIndex:0];
    [ApxorSDK setUserIdentifier:userID];
}

- (void)setUserCustomInfo:(CDVInvokedUrlCommand*)command
{
    NSDictionary *info = [command.arguments objectAtIndex:0];
    [ApxorSDK setUserCustomInfo:info];
}

- (void)setSessionCustomInfo:(CDVInvokedUrlCommand*)command
{
    NSDictionary *info = [command.arguments objectAtIndex:0];
    [ApxorSDK setSessionCustomInfo:info];
}

- (void)logAppEvent:(CDVInvokedUrlCommand*)command
{
    NSString *eventName = [command.arguments objectAtIndex:0];
    NSDictionary *info = [command.arguments objectAtIndex:1];
    [ApxorSDK logAppEventWithName:eventName info:info];
}

- (void)logClientEvent:(CDVInvokedUrlCommand*)command
{
    NSString *eventName = [command.arguments objectAtIndex:0];
    NSDictionary *info = [command.arguments objectAtIndex:1];
    [ApxorSDK logClientEventWithName:eventName info:info];
}

- (void)setUserAcquisitionSource:(CDVInvokedUrlCommand*)command
{
    NSLog(@"setUserAcquisitionSource is a no-op in iOS");
}

- (void)logNavigationEvent:(CDVInvokedUrlCommand*)command
{
    NSString* screenName = [command.arguments objectAtIndex:0];
    [ApxorSDK logScreenWithName:screenName];
}

- (void)trackScreen:(CDVInvokedUrlCommand*)command
{
    NSString* screenName = [command.arguments objectAtIndex:0];
    [ApxorSDK logScreenWithName:screenName];
}

- (void)setPushRegistrationToken:(CDVInvokedUrlCommand*)command
{
    NSLog(@"setPushRegistrationToken is a no-op in iOS");
}

- (void)startSession:(CDVInvokedUrlCommand*)command
{
    NSLog(@"startSession is a no-op in iOS");
}

- (void)endSession:(CDVInvokedUrlCommand*)command
{
    NSLog(@"endSession is a no-op in iOS");
}

- (void)login:(CDVInvokedUrlCommand*)command
{
    NSLog(@"login is a no-op in iOS");
}

- (void)logout:(CDVInvokedUrlCommand*)command
{
    NSLog(@"logout is a no-op in iOS");
}

- (void)optOut:(CDVInvokedUrlCommand*)command
{
    NSLog(@"optOut is a no-op in iOS");
}

- (void)registerDeeplinkHandler:(CDVInvokedUrlCommand*)command
{
    deeplinkCommand = command;
}

/*
*   Internal methods
*/
- (void)_internalEvent:(CDVInvokedUrlCommand*)command
{
    NSString *eventName = [command.arguments objectAtIndex:0];
    NSString *uuid = [command.arguments objectAtIndex:1];
    NSString *name = [command.arguments objectAtIndex:2];
    [APXRTAUtilities logActionEventWithTitle:eventName messageName:name identifier:uuid];
}

- (void)_internalUpdateCount:(CDVInvokedUrlCommand*)command
{
    NSString *uuid = [command.arguments objectAtIndex:0];
    [[APXContextEvaluator sharedInstance] updateCountForConfigWithIdentifier:uuid];
}

- (void)onEvent:(APXEvent *) event {
    
    NSDictionary *info = [event getAdditionalInfo];
    if (event.eventType == APXEventTypeApp && [event.identifier isEqualToString:INLINE_SHOWN]) {
        //if inline_shown then add touch listener on webview
        dispatch_async(dispatch_get_main_queue(), ^{
            UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(didTouch:)];
            [tap setDelegate:self];
            [self.webView addGestureRecognizer:tap];
        });
    } else if (event.eventType == APXEventTypeInternal && [event.identifier isEqualToString:HANDLE_DEEPLINK]) {
        dispatch_async(dispatch_get_main_queue(), ^{
            if (deeplinkCommand && info[@"url"]) {
                NSString *url = info[@"url"];
                CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:url];
                [pluginResult setKeepCallbackAsBool:YES];
                [self.commandDelegate sendPluginResult:pluginResult callbackId:deeplinkCommand.callbackId];
            }
        });
    }
}

- (void)didTouch:(UITapGestureRecognizer *)recognizer
{
    NSString *js = [NSString stringWithFormat:@"ApxorRTM&&ApxorRTM.removeAll()"];
    [self.commandDelegate evalJs:js];

    //remove it
    WKWebView *webView = (WKWebView*) self.webView;
    [webView removeGestureRecognizer:recognizer];
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {
    return YES;
}

@end
