#import "BluestackManager.h"
#import <BlueStackSDK/MNGAdsSDKFactory.h>
#import <React/RCTLog.h>

@interface BluestackManager () <MNGAdsSDKFactoryDelegate>

@property (nonatomic, strong) NSMutableArray<RCTPromiseResolveBlock> *resolveList;
@property (nonatomic, strong) NSMutableArray<RCTPromiseRejectBlock> *rejectList;

@end

@implementation BluestackManager
@synthesize bridge = _bridge;
int EVENT_INIT_SUCCESS = 1;
BOOL isInitInProgress = false;

RCT_EXPORT_MODULE(BluestackManager)

+ (BOOL)requiresMainQueueSetup {
  return YES;
}

- (instancetype)init {
  if (self = [super init]) {
    _resolveList = [NSMutableArray array];
    _rejectList = [NSMutableArray array];
  }
  return self;
}

- (void)setBridge:(RCTBridge *)bridge
{
  _bridge = bridge;
}

RCT_EXPORT_METHOD(
    initializeSDK:(NSString *)appId
    enableDebugger:(BOOL)enableDebug
    resolver:(RCTPromiseResolveBlock)resolve
    rejecter:(RCTPromiseRejectBlock)reject
)
{
    // Add the resolve and reject blocks
    [self.resolveList addObject:resolve];
    [self.rejectList addObject:reject];

    if (!isInitInProgress){
        isInitInProgress = true;
        [MNGAdsSDKFactory setDelegate:self];
        [MNGAdsSDKFactory setDebugModeEnabled:enableDebug];
        [MNGAdsSDKFactory initWithAppId:appId];
    }
}

-(void)MNGAdsSDKFactoryDidFinishInitializing{
    NSLog(@"MNGAds sucess initialization");
    
    // resolve all promises in the list
    for (RCTPromiseResolveBlock resolve in self.resolveList) {
        resolve(@(EVENT_INIT_SUCCESS));
    }

    [self cleanUpAd];
}

-(void)MNGAdsSDKFactoryDidFailInitializationWithError:(NSError *)error {
    NSLog(@"MNGAds failed initialization");
    
    // reject all promises in the list
    for (RCTPromiseRejectBlock reject in self.rejectList) {
        reject(@"SDK_FAILED_TO_INIT", [error localizedDescription], error);
    }

    [self cleanUpAd];
}

- (void)cleanUpAd
{
    isInitInProgress = false;
    [self.resolveList removeAllObjects];
    [self.rejectList removeAllObjects];
}
@end
