//
//  AppticsAppUpdateModule.m
//  AppticsModule
//
//  Created by Saravanan S on 31/10/23.
//  Copyright © 2023 Facebook. All rights reserved.
//

#import "APRemoteConfigModule.h"
#import <AppticsRemoteConfig/AppticsRemoteConfig.h>
#import <Apptics/Apptics.h>

@implementation APRemoteConfigModule RCT_EXPORT_MODULE()

//- (NSArray<NSString *> *)supportedEvents {
//  return @[@"APRemoteConfigUpdateNotification"];
//}

#pragma mark — Remote Config Methods

//RCT_EXPORT_METHOD(fetchValue){
//    [APRemoteConfig enable: true];
//}
//
//RCT_EXPORT_METHOD(fetchAndActivate){
////    [[APRemoteConfig shared] fetchAndActivate];
//
//}
//
//RCT_EXPORT_METHOD(fetchRemoteConfigWithCompletion:(RCTResponseSenderBlock)callback) {
//
//    APRemoteConfig *remoteConfig = [APRemoteConfig shared];
//          [remoteConfig fetchRemoteConfigWithCompletion:^(APRemoteConfigFetchStatus status) {
//              if (status == APRemoteConfigFetchStatusSuccess || status == APRemoteConfigFetchStatusUpToDate){
//                  callback(@[@(status)]);
//              }
//          }];
//}
//
////RCT_EXPORT_METHOD(fetchRemoteConfigWithCompletion:(RCTPromiseResolveBlock)resolve
////                  rejecter:(RCTPromiseRejectBlock)reject) {
////
////    APRemoteConfig *remoteConfig = [APRemoteConfig shared];
////      [remoteConfig fetchRemoteConfigWithCompletion:^(APRemoteConfigFetchStatus status) {
////          resolve(@(status));
////          if (status == APRemoteConfigFetchStatusSuccess || status == APRemoteConfigFetchStatusUpToDate){
////              [remoteConfig activateFetched];
////              NSString *primaryColor = remoteConfig[@"primaryColor"].stringValue;
////          }
////      }];
////
//////    reject(@"ERROR", @"No update found", [NSError errorWithDomain:@"Apptics" code:400 userInfo:@{@"type":@"error", @"message":@"No update found"}]);
//////    resolve(updateData);
////
////
////}
//

RCT_EXPORT_METHOD(fetchValue:(NSString*)key coldFetch:(BOOL)coldFetch fallbackWithOfflineValue:(BOOL)fallbackWithOfflineValue resolve:(RCTPromiseResolveBlock)resolve
                  reject:(RCTPromiseRejectBlock)reject) {
        
    NSTimeInterval currentTime = [[NSDate date] timeIntervalSince1970];
    NSTimeInterval timeDifference = currentTime - self.lastFetchedTime;
        
    if (coldFetch){
        if (self.lastFetchedTime == 0 || timeDifference > 10){
            
            self.lastFetchedTime = [[NSDate date] timeIntervalSince1970];
            
            [[APRemoteConfig shared] fetchRemoteConfigWithCompletion:^(APRemoteConfigFetchStatus status) {
                if (status == APRemoteConfigFetchStatusSuccess || status == APRemoteConfigFetchStatusUpToDate){
                    if ([[APRemoteConfig shared] activateFetched] == true){
                        [self getValue:key resolve:resolve rejecter:reject];
                    }else{
                        reject(@"ERROR", @"Value not found", [NSError errorWithDomain:@"Apptics" code:400 userInfo:@{@"type":@"error", @"message":@"Value not found"}]);
                    }
                }else if (status == APRemoteConfigFetchStatusFailure){
                    reject(@"ERROR", @"Fetch failed", [NSError errorWithDomain:@"Apptics" code:400 userInfo:@{@"type":@"error", @"message":@"Failed to fetch data from the server"}]);
                }
            }];
        }else if (fallbackWithOfflineValue){
            if ([APRemoteConfig shared].lastFetchStatus != APRemoteConfigFetchStatusFailure){
                [self getValue:key resolve:resolve rejecter:reject];
            }else{
                reject(@"ERROR", @"Fetch failed", [NSError errorWithDomain:@"Apptics" code:400 userInfo:@{@"type":@"error", @"message":@"Failed to fetch data from the server"}]);
            }
        }else{
            reject(@"ERROR", @"Fetch failed", [NSError errorWithDomain:@"Apptics" code:400 userInfo:@{@"type":@"error", @"message":[NSString stringWithFormat:@"Last fetch happened before %f sec, try after %f sec", timeDifference, (10 - timeDifference)]}]);
            
        }
    }else{
        if (self.lastFetchedTime == 0){
            
            self.lastFetchedTime = [[NSDate date] timeIntervalSince1970];
            
            [[APRemoteConfig shared] fetchRemoteConfigWithCompletion:^(APRemoteConfigFetchStatus status) {
                if (status == APRemoteConfigFetchStatusSuccess || status == APRemoteConfigFetchStatusUpToDate){
                    if ([[APRemoteConfig shared] activateFetched] == true){
                        [self getValue:key resolve:resolve rejecter:reject];
                    }else{
                        reject(@"ERROR", @"Value not found", [NSError errorWithDomain:@"Apptics" code:400 userInfo:@{@"type":@"error", @"message":@"Value not found"}]);
                    }
                }else if (status == APRemoteConfigFetchStatusFailure){
                    reject(@"ERROR", @"Fetch failed", [NSError errorWithDomain:@"Apptics" code:400 userInfo:@{@"type":@"error", @"message":@"Failed to fetch data from the server"}]);
                }
            }];
        }else{
            if ([APRemoteConfig shared].lastFetchStatus == APRemoteConfigFetchStatusFailure){
                reject(@"ERROR", @"Fetch failed", [NSError errorWithDomain:@"Apptics" code:400 userInfo:@{@"type":@"error", @"message":@"Failed to fetch data from the server"}]);
            }else if ([APRemoteConfig shared].lastFetchStatus == APRemoteConfigFetchStatusNotYetFetched){
                reject(@"ERROR", @"Fetchhing inprogress", [NSError errorWithDomain:@"Apptics" code:400 userInfo:@{@"type":@"error", @"message":@"Fetching data from serve"}]);
            }else{
                [self getValue:key resolve:resolve rejecter:reject];
            }
        }
    }
}

RCT_EXPORT_METHOD(getValue:(NSString*) key resolve:(RCTPromiseResolveBlock)resolve
                  rejecter:(RCTPromiseRejectBlock)reject) {
    APRemoteConfigValue *value = [APRemoteConfig shared][key];
    if (value != nil && value.stringValue != nil){
        resolve(value.stringValue);
    }else{
        reject(@"ERROR", @"Not found", [NSError errorWithDomain:@"Apptics" code:400 userInfo:@{@"type":@"error", @"message":[NSString stringWithFormat:@"Value not found for the key '%@'", key]}]);
    }
}

RCT_EXPORT_METHOD(setCustomConditionValue:(NSString *)conditionKey conditionValue:(NSString*)conditionValue){
    [[APRemoteConfig shared] addCustomCriteria:conditionKey value:conditionValue];
}

//addCustomCriteria

//RCT_EXPORT_BLOCKING_SYNCHRONOUS_METHOD(getStringValue:(NSString *) key)  {
//    APRemoteConfigValue *value = [APRemoteConfig shared][key];
//    return value.stringValue;
//}
//
//RCT_EXPORT_BLOCKING_SYNCHRONOUS_METHOD(getNumberValue:(NSString *)key) {
//    APRemoteConfigValue *value = [APRemoteConfig shared][key];
//    return value.numberValue;
//}
//
//RCT_EXPORT_BLOCKING_SYNCHRONOUS_METHOD(getDataValue:(NSString *)key) {
//    APRemoteConfigValue *value = [APRemoteConfig shared][key];
//
//        // Convert NSData to an array of bytes
//        NSData *data = value.dataValue;
//        const Byte *bytes = (const Byte *)[data bytes];
//        NSUInteger length = [data length];
//
//        // Create a JavaScript array from the bytes
//        NSMutableArray *jsArray = [NSMutableArray arrayWithCapacity:length];
//        for (NSUInteger i = 0; i < length; i++) {
//            [jsArray addObject:[NSNumber numberWithInt:bytes[i]]];
//        }
//
//    return jsArray;
//}
//
//RCT_EXPORT_BLOCKING_SYNCHRONOUS_METHOD(getBoolValue:(NSString *)key) {
//    APRemoteConfigValue *value = [APRemoteConfig shared][key];
//    return @(value.boolValue);
//}
//
//RCT_EXPORT_BLOCKING_SYNCHRONOUS_METHOD(getJsonValue:(NSString *)key) {
//    APRemoteConfigValue *value = [APRemoteConfig shared][key];
//    return value.jsonValue;
//}

#ifdef RCT_NEW_ARCH_ENABLED
- (std::shared_ptr<facebook::react::TurboModule>)getTurboModule:
    (const facebook::react::ObjCTurboModule::InitParams &)params
{
  return std::make_shared<facebook::react::NativeAPRemoteConfigModuleSpecJSI>(params);
}
#endif

@end
