//  Copyright 2021 VMWare


#import "CDVWS1Intelligence.h"
#import "WS1Intelligence.h"
#import "WS1PluginInterface.h"
#import "WS1Constants.h"

static NSString *const WS1JavascriptXMLHttpRequest = @"JavascriptXMLHttpRequest";

@implementation CDVWS1Intelligence

- (void)pluginInitialize {
  
}

// Initialization

- (void)ws1IntelligenceInit:(CDVInvokedUrlCommand *)command {
  [self.commandDelegate runInBackground:^{
    NSDictionary *argsDict = command.arguments[0];
    NSString *appId = [argsDict objectForKey:@"iosAppID"];
    NSLog(@"Initializing WS1 Intelligence SDK for Cordova application with app id %@", appId);
    //[WS1Intelligence enableWithAppID:appId];

    WS1Config *config = [WS1Config defaultConfig];
    config.monitorNSURLConnection = NO;
    config.monitorNSURLSession = NO;
    [WS1Intelligence enableWithAppID:appId config:config];
  }];
}

- (void)ws1IntelligenceSetLoggingLevel:(CDVInvokedUrlCommand *)command {
   [self.commandDelegate runInBackground:^{
      NSInteger loggingLevel = [command.arguments[0] integerValue];
      [WS1Intelligence setLoggingLevel:loggingLevel];
   }];
}

// Breadcrumbs

- (void)ws1IntelligenceLeaveBreadcrumb:(CDVInvokedUrlCommand *)command {
  [self.commandDelegate runInBackground:^{
    NSString *breadcrumb = command.arguments[0];
    [WS1Intelligence leaveBreadcrumb:breadcrumb];
  }];
}

- (void)ws1IntelligenceSetAsyncBreadcrumbMode:(CDVInvokedUrlCommand *)command {
  [self.commandDelegate runInBackground:^{
    BOOL asyncBreadcrumbsEnabled = [command.arguments[0] boolValue];
    [WS1Intelligence setAsyncBreadcrumbMode:asyncBreadcrumbsEnabled];
  }];
}

// User Flows

- (void)ws1IntelligenceBeginUserFlow:(CDVInvokedUrlCommand *)command {
  [self.commandDelegate runInBackground:^{
    NSString *userFlowName = command.arguments[0];
    [WS1Intelligence beginUserFlow:userFlowName];
  }];
}

- (void)ws1IntelligenceEndUserFlow:(CDVInvokedUrlCommand *)command {
  [self.commandDelegate runInBackground:^{
    NSString *userFlowName = command.arguments[0];
    [WS1Intelligence endUserFlow:userFlowName];
  }];
}

- (void)ws1IntelligenceFailUserFlow:(CDVInvokedUrlCommand *)command {
  [self.commandDelegate runInBackground:^{
    NSString *userFlowName = command.arguments[0];
    [WS1Intelligence failUserFlow:userFlowName];
  }];
}

- (void)ws1IntelligenceCancelUserFlow:(CDVInvokedUrlCommand *)command {
  [self.commandDelegate runInBackground:^{
    NSString *userFlowName = command.arguments[0];
    [WS1Intelligence cancelUserFlow:userFlowName];
  }];
}

// Exceptions

- (void)ws1IntelligenceLogHandledException:(CDVInvokedUrlCommand *)command {
  [self.commandDelegate runInBackground:^{
    NSString *name = command.arguments[0];
    NSString *reason = command.arguments[1];
    NSString *stack = command.arguments[2];

    stack = [self deleteStackFillerInformation:stack];

    [WS1PluginInterface logPluginExceptionWithName:name
                                            reason:reason
                                             stack:stack
                                  pluginIdentifier:WS1PluginIdentifierCordova
                                           handled:YES];
  }];
}

- (void)ws1IntelligenceLogUnhandledException:(CDVInvokedUrlCommand *)command {
  [self.commandDelegate runInBackground:^{
    NSString *name = command.arguments[0];
    NSString *reason = command.arguments[1];
    NSString *stack = command.arguments[2];

    stack = [self deleteStackFillerInformation:stack];

    [WS1PluginInterface logPluginExceptionWithName:name
                                            reason:reason
                                             stack:stack
                                  pluginIdentifier:WS1PluginIdentifierCordova
                                           handled:NO];
  }];
}

// Network Request

- (void)ws1IntelligenceLogNetworkRequest:(CDVInvokedUrlCommand *)command {
  [self.commandDelegate runInBackground:^{
    NSString *method = command.arguments[0];
    NSURL *url = [NSURL URLWithString:command.arguments[1]];
    NSUInteger latencyMillis = [command.arguments[2] unsignedLongValue];
    NSTimeInterval latency = latencyMillis / 1000.0;
    NSUInteger bytesRead = [command.arguments[3] unsignedIntegerValue];
    NSUInteger bytesSent = [command.arguments[4] unsignedIntegerValue];
    NSInteger responseCode = [command.arguments[5] integerValue];
    NSObject *errorCode = command.arguments[6];

    NSError *error = nil;

    if ([errorCode isKindOfClass:[NSNull class]]) {
        // Strictly, caller should always be passing an integer errorCode,
        // but we let errorCode = null slide without remarking.
    } else if ([errorCode isKindOfClass:[NSNumber class]]) {
        // Convert number to integer, even if it is float.
        error = [[NSError alloc] initWithDomain:WS1JavascriptXMLHttpRequest
                                           code:[(NSNumber *)errorCode integerValue]
                                       userInfo:nil];
    } else {
        // Complain and carry on as if errorCode = 0 was passed, hence leave error = nil .
        NSLog(@"errorCode == %@ should be an integer", errorCode);
    }

    [WS1Intelligence logNetworkRequest:method
                                   url:url
                               latency:latency
                             bytesRead:bytesRead
                             bytesSent:bytesSent
                          responseCode:responseCode
                                 error:error];
  }];
}

// Location

- (void)ws1IntelligenceLogLocation:(CDVInvokedUrlCommand *)command {
  [self.commandDelegate runInBackground:^{

    NSNumber *latitude = command.arguments[0];
    NSNumber *longitude = command.arguments[1];

    [WS1Intelligence updateLocationToLatitude:[latitude doubleValue]
                                    longitude:[longitude doubleValue]];
  }];
}

// Opt Out Status

- (void)ws1IntelligenceSetOptOutStatus:(CDVInvokedUrlCommand *)command {
  [self.commandDelegate runInBackground:^{
    BOOL status = [command.arguments[0] boolValue];
    [WS1Intelligence setOptOutStatus:status];
  }];
}

- (void)ws1IntelligenceGetOptOutStatus:(CDVInvokedUrlCommand *)command {
  [self.commandDelegate runInBackground:^{
    BOOL status = [WS1Intelligence getOptOutStatus];

    CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK
                                                        messageAsBool:(BOOL)status];

    [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
  }];
}

// User UUID

- (void)ws1IntelligenceGetUserUUID:(CDVInvokedUrlCommand *)command {
  [self.commandDelegate runInBackground:^{
    NSString *userUUID = [WS1Intelligence getUserUUID];

    CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK
                                                      messageAsString:userUUID];

    [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
  }];
}

// didCrashOnLastLoad

- (void)ws1IntelligenceDidCrashOnLastLoad:(CDVInvokedUrlCommand *)command {
  [self.commandDelegate runInBackground:^{
    BOOL didCrash = [WS1Intelligence didCrashOnLastLoad];

    CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK
                                                        messageAsBool:(BOOL)didCrash];

    [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
  }];
}

// Username

- (void)ws1IntelligenceSetUsername:(CDVInvokedUrlCommand *)command {
  [self.commandDelegate runInBackground:^{
    NSString *username = command.arguments[0];
    [WS1Intelligence setUsername:username];
  }];
}

// Examples below
//
// FunctionC@file:///Users/tshi/Library/Application%20Support/iPhone%20Simulator/6.1/Applications/29A502DF-F664-434A-94C6-12AAA20BCF33/HelloWorld.app/www/js/app.js:30
// -> FunctionC@HelloWorld.app/www/js/app.js:30
//
// {anonymous}("Error: Error!","file:///Users/tshi/Library/Application%20Support/iPhone%20Simulator/6.1/Applications/29A502DF-F664-434A-94C6-12AAA20BCF33/HelloWorld.app/www/js/app.js",22)
// -> {anonymous}("Error: Error!","js/app.js",22)

- (NSString *)deleteStackFillerInformation:(NSString *) stack {
  NSString *appName = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleDisplayName"];
  NSString *pattern = [NSString stringWithFormat:@"file:///.*(?=%@)", appName];
  NSError *error = NULL;
  NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern
                                                                         options:NSRegularExpressionCaseInsensitive
                                                                           error:&error];
  return [regex stringByReplacingMatchesInString:stack options:0 range:NSMakeRange(0, [stack length]) withTemplate:@""];
}

@end
