//
//  CrashReportUploadOperation.m
//  HelloAnalytics
//
//  Created by Saravanan S on 08/08/18.
//  Copyright © 2018 Saravanan S. All rights reserved.
//

#import "APCrashReportUploadOperation.h"
#import <React/RCTLog.h>

#if __has_include(<Apptics/Apptics.h>)
#import <Apptics/Apptics.h>
//#import <Apptics/APLog.h>
#import <Apptics/ZASystemInfo.h>
#import <Apptics/ZAFileManager.h>
#import <Apptics/ZANetworking.h>
#import <Apptics/ZAPIIManager.h>
#import <Apptics/APJWTWrapper.h>
#import <Apptics/NSData+APGunZip.h>
#endif

@implementation APCrashReportUploadOperation

NSString *notificationName=@"APRCTCrashUploadSuccessNotification";

- (id)initWithCrashReport:(NSDictionary *)crashReport{
  self = [super init];
  
  if (!self) return nil;
  
  NSMutableDictionary *crash = (NSMutableDictionary*)[crashReport mutableCopy];
    [self setReportIds:(crashReport[@"reportIDs"]) ? crashReport[@"reportIDs"] : @[]];
    [crash removeObjectForKey:@"reportIDs"];
      
    NSString *userId = crashReport[@"userid"];
    NSString *anonid = crashReport[@"anonid"];
    self.isfatal = crashReport[@"isfatal"];
    
    [crash removeObjectForKey:@"userid"];
    [crash removeObjectForKey:@"anonid"];
    [crash removeObjectForKey:@"isfatal"];
    [crash removeObjectForKey:@"size"];
    
    NSString *params = [[ZANetworking sharedManager] setDefaultParams];
    
    params = [[ZANetworking sharedManager] setIdentificationParams:params userID:userId anonID:anonid];
    if (self.isfatal.boolValue == true){
        notificationName=@"APRCTCrashUploadSuccessNotification";
    }else{
        notificationName=@"APRCTNonFatalsUploadSuccessNotification";
    }
    self.aaaUtil = [[ZANetworking sharedManager] getAuthindicatorForUserID:userId anonID:anonid];
//    if (za_isNotEmpty(anonid)){
//        params = [NSString stringWithFormat:@"anondeviceid=%@", anonid];
//    }else{
//        params = [NSString stringWithFormat:@"deviceid=%@&userid=%@", [ZAPIIManager getInstance].regDeviceId, userId];
//    }
        
    self.params = params;
  [self setCrashReport:crash];
  return self;
}

- (id)initWithFileName:(NSString *)fileName{
  self = [super init];
  
  if (!self) return nil;
  [self setFileName:fileName];
  return self;
}

- (void)dealloc {
  _fileName = nil;
}

- (void)main {
  [self sendReports:self.crashReport];
}

-(void) parseData : (NSDictionary *) response withSuccess : (void (^)(long long value))success;{
    NSString *result = response[@"result"];
    if ([result isEqualToString:@"success"]){
      success(1);
      return;
    }else{
    [ZANetworking processError:response aaaUtil:self.aaaUtil];
      success(0);
      return;
    }
}

-(void) sendReports:(NSDictionary *)report
{
  // TODO: Write a priority based network layer here
  // Interwebzz code goes here
    [self.aaaUtil getTokenWithSuccess:^(NSString * _Nonnull token) {
  NSURLSessionConfiguration *sessionConfig = [NSURLSessionConfiguration defaultSessionConfiguration];
  sessionConfig.timeoutIntervalForRequest = 120.0;//2min allowance; iOS default is 60 seconds.
  sessionConfig.timeoutIntervalForResource = 120.0;//2min; iOS Default is 7 days
  
  NSURLSession *session = [NSURLSession sessionWithConfiguration:sessionConfig];
        NSDictionary *crashDictionary = report;
    NSString *urlString = self.url.absoluteString;
    if (self.isfatal.boolValue == true){
        urlString = [NSString stringWithFormat:@"%@/fatal?%@", urlString, self.params];
    }else{
        urlString = [NSString stringWithFormat:@"%@/nonfatal?%@", urlString, self.params];
    }
    
  NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlString]];
  
  if ([ZANetworking sharedManager].userAgent && ![[ZANetworking sharedManager].userAgent isEqualToString:@""])
  {
    [request setValue:[ZANetworking sharedManager].userAgent forHTTPHeaderField:@"User-Agent"];
  }
  
  [[ZANetworking sharedManager] setHTTPHeaderField:request forPath:JURLPathCrash];
  [request setValue:[NSString stringWithFormat:@"Bearer %@",token] forHTTPHeaderField:@"Authorization"];
  
    if ([ZAFileManager sharedInstance].enableGzip){
        [request setValue:@"gzip" forHTTPHeaderField:@"Content-Encoding"];
    }else{
        [request addValue:@"text/plain" forHTTPHeaderField:@"Content-Type"];
    }
        
  request.HTTPMethod = @"POST";
  request.HTTPShouldHandleCookies = false;
  NSError *error;
        
  RCTLog(@"Http headers -> %@", request.allHTTPHeaderFields);
                
  @try {
    //NSData *POSTHttpBody = [[APJWTWrapper sharedManager] encodeWithJWT:crashDictionary];
      NSData *postData = [NSJSONSerialization dataWithJSONObject:crashDictionary options:0 error:nil];
      NSData *POSTHttpBody;
      if ([ZAFileManager sharedInstance].enableGzip){
          NSData *compressedData = [postData ap_gzippedDataWithCompressionLevel:1.0];
              if (!compressedData) {
                  RCTLog(@"Compression failed");
              }
          POSTHttpBody = [[APJWTWrapper sharedManager] encodeDataWithJWT:compressedData];
      }else{
          POSTHttpBody = [[APJWTWrapper sharedManager] encodeWithJWT:crashDictionary];
      }
    NSString *postLength = [NSString stringWithFormat:@"%lu", (unsigned long)[POSTHttpBody length]];
    [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
    [request setHTTPBody:POSTHttpBody];
  }
  @catch (NSException *exception) {
    RCTLog(@"%@ exception encoding crash data: %@", self, exception);
//      APTrackException(exception);
  }
  if (error){
    RCTLog(@"%@ error encoding crash data: %@", self, error);
//    APTrackError(error);
  }else{
      RCTLog(@"Request made -> %@",request.URL.absoluteString);
      RCTLog(@"Http headers -> %@", request.allHTTPHeaderFields);
      [self beginBackgroundUpdateTask];
      [[session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error)
        {
          RCTLog(@"Response received -> %@",response.URL.absoluteString);
          RCTLog(@"Response data -> %@",[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
          if (!error)
          {
            NSError *jsonParsingError;
            NSDictionary *responseJSON = [NSJSONSerialization JSONObjectWithData:data options:0 error:&jsonParsingError];
            
            if (responseJSON)
            {
              RCTLog(@"Data received -> %@",responseJSON);
              [self parseData:responseJSON withSuccess:^(long long value) {
                if (value > 0){
//                  #if KSCR_PRIVATE || PLCR_PRIVATE
                  [[NSNotificationCenter defaultCenter] postNotificationName:notificationName object:self.reportIds];
//                  #else
//                  [[NSNotificationCenter defaultCenter] postNotificationName:@"APRCTCrashUploadSuccessNotification" object:self.fileName];
//                  #endif
                }
              }];
            }else{
              RCTLog(@"Error while parsing crash upload response -> %@",jsonParsingError);
            }
          }
          else
          {
            RCTLog(@"Error while uploading crash report -> %@",error);
          }
          [self endBackgroundUpdateTask];
        }]resume];
  }
    }];
}

- (void) beginBackgroundUpdateTask
{
#if !TARGET_OS_OSX && !TARGET_OS_WATCH
    self.backgroundUpdateTask = [[UIApplication performSelector:@selector(sharedApplication)] beginBackgroundTaskWithExpirationHandler:^{
        [self endBackgroundUpdateTask];
    }];
#endif
}

- (void) endBackgroundUpdateTask
{
#if !TARGET_OS_OSX && !TARGET_OS_WATCH
    [[UIApplication performSelector:@selector(sharedApplication)] endBackgroundTask: self.backgroundUpdateTask];
    self.backgroundUpdateTask = UIBackgroundTaskInvalid;
#endif
}
@end
