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

#import "APAppUpdateModule.h"
#import <AppticsInAppUpdate/AppticsInAppUpdate.h>
#import <Apptics/Apptics.h>

@implementation AppticsAppUpdateModule RCT_EXPORT_MODULE()

#pragma mark — App Update apis

///**
// This method returns the in app update details.
// */
//
//RCT_EXPORT_BLOCKING_SYNCHRONOUS_METHOD(getUpdateDetails){
//    if (!za_isNotEmpty([ZAPIIManager getInstance].regDeviceId) || ![APAppUpdateManager sharedManager].gotResponse){
//        return nil;
//    }
//    NSDictionary *JSONDict = [ZAKeyChainWrapper dictionaryForKey:@"appUpdateData"];
//    return JSONDict;
//}

/**
 Apptics will present update popup up on top of any view controller on navigation stack.
 */

RCT_EXPORT_METHOD(showNewVersionAlert){
    [APAppUpdateManager checkForUpdateAvailability:nil with:nil];
}

/**
 Implement your own custom in app update popup using checkForUpdate method, parse the json value returned by this method and handle the cases on your own.
 */

RCT_EXPORT_METHOD(checkForUpdate:(RCTPromiseResolveBlock)resolve
                  reject:(RCTPromiseRejectBlock)reject) {
    [APAppUpdateManager checkForUpdateAvailability:^(NSDictionary * _Nullable updateInfo) {
        NSDictionary *updateData = [self convertUpdateDataToJson:updateInfo];
        if (updateData == nil){
            reject(@"ERROR", @"No update found", [NSError errorWithDomain:@"Apptics" code:400 userInfo:@{@"type":@"error", @"message":@"No update found"}]);
        }else{
            resolve(updateData);
        }
    } with:nil];

}

/**
 Set back the actions for custom in app update.
 @param updateId update id that you will get in checkForupdate callback handler.
 @param stat set appropriate actions listed in the enum of UpdateStats.
 */

RCT_EXPORT_METHOD(sendUpdatesEngagementStats : (NSString*) updateId engagement : (NSString *) stat){
    [[APAppUpdateManager sharedManager] updateStatsWithAction:stat AndUpdateId:@(updateId.longLongValue)];
}

-(NSDictionary*) convertUpdateDataToJson: (NSDictionary*) jsonObject{
    if (jsonObject){
        NSDictionary *popupInfo = jsonObject[@"popupinfo"];
        NSDictionary *updateDetails = jsonObject[@"updatedetails"];
        if (popupInfo && updateDetails){
            return @{
                @"updateid" : za_safeNumber(jsonObject[@"updateid"]),
                @"currentversion" : za_safeString(jsonObject[@"currentversion"]),
                @"featureTitle" : za_safeString(popupInfo[@"title"]),
                @"features" : za_safeString(popupInfo[@"description"]),
                @"remindMeLaterText" : za_safeString(popupInfo[@"remindmelater"]),
                @"updateNowText" : za_safeString(popupInfo[@"updatenow"]),
                @"neverAgainText" : za_safeString(popupInfo[@"ignore"]),
                @"option" : za_safeNumber(updateDetails[@"option"]),
                @"reminderDays" : za_safeNumber(updateDetails[@"reminder"]),
                @"forceInDays" : za_safeNumber(updateDetails[@"toforce"]),
                @"alertType" : za_safeNumber(updateDetails[@"popuptype"]),
                @"customStoreUrl" : za_safeString(updateDetails[@"storeurl"])
            };
        }

    } return nil;
}

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

@end
