//
//  BluestackInterstitialAdManager.m
//  @azerion/bluestack-sdk-react-native
//
//  Created by anypli on 17/5/2022.
//

#import "BluestackInterstitialAdManager.h"
#import "BluestackAdsCommon.h"
#import <React/RCTUtils.h>
#import <React/RCTLog.h>
#import <BlueStackSDK/MNGAdsSDKFactory.h>
@interface BluestackInterstitialAdManager ()<MNGAdsAdapterInterstitialDelegate,MNGClickDelegate>{
    MNGAdsSDKFactory *interstitialAdsFactory;
}

@property (nonatomic, strong) UIViewController *adViewController;
@property (nonatomic) bool didClick;
@property (nonatomic) bool showWhenLoaded;

@end
@implementation BluestackInterstitialAdManager{
     bool hasListeners;
}

//@synthesize bridge = _bridge;
NSString *  EVENT_LOADED_AD = @"onAdLoaded";
NSString *  EVENT_DISAPPEAR_AD = @"onAdDismissed";
NSString *  EVENT_DID_SHOWN_AD = @"onAdDisplayed";
NSString *  EVENT_AD_CLICKED = @"onAdClicked";
NSString *  EVENT_AD_ERROR= @"onAdFailedError";
NSString *  EVENT_AD_MESSAGE_ERROR_KEY= @"errorMessage";

NSString * EVENT_KEY = @"interstitialEvent";
NSString * EVENT_NAME = @"InterstitialAdEvent";

RCT_EXPORT_MODULE(BluestackInterstitialAdManager)

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

RCT_EXPORT_METHOD(
  loadAd:(NSString *)placementId
  autoDisplay:(BOOL)autoDisplay
  withPreference:(NSString *)preferenceJSON             
)
{
  
    [self cleanUpAd];

    
    if (interstitialAdsFactory.isBusy) {
        NSLog(@"Ads Factory is busy");
        return;
    }
    [interstitialAdsFactory releaseMemory];
    interstitialAdsFactory = [[MNGAdsSDKFactory alloc]init];
    interstitialAdsFactory.clickDelegate = self;
    interstitialAdsFactory.interstitialDelegate = self;
    interstitialAdsFactory.viewController = RCTPresentedViewController();
    
    /**
     * MNGPrefence is the same for all ad types
     * @important: your application can be rejected by Apple if you use the device's location only for advertising
     **/
    //MNGPreference *preferences = [[MNGPreference alloc]init];
    MNGPreference *preferences = [BluestackAdsCommon getMNGPreference:preferenceJSON];
    
    interstitialAdsFactory.placementId = placementId;
    
    dispatch_async(dispatch_get_main_queue(), ^{
        [self->interstitialAdsFactory loadInterstitialWithPreferences:preferences autoDisplayed:autoDisplay];
    });
}

RCT_EXPORT_METHOD(
 displayAd
  ) {
    dispatch_async(dispatch_get_main_queue(), ^{
        [self->interstitialAdsFactory showAdFromRootViewController:RCTPresentedViewController() animated:YES];
    });
}

#pragma mark - RCTEventEmitter

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

// Will be called when this module's first listener is added.
-(void)startObserving {
    hasListeners = YES;
    NSLog(@"startObserving");

}

// Will be called when this module's last listener is removed, or on dealloc.
-(void)stopObserving {
    NSLog(@"stopObserving");

    hasListeners = NO;
}

- (void)sendEventWithBody:(NSString*)body {
  if (hasListeners) {
    [self sendEventWithName:EVENT_NAME body:@{EVENT_KEY:body}];
  }
}

#pragma mark - MNGAdsAdapterInterstitialDelegate

-(void)adsAdapterInterstitialDidLoad:(MNGAdsAdapter *)adsAdapter{
//    NSLog(@"adsAdapterInterstitialDidLoad");
  
   if (_showWhenLoaded) {
       dispatch_async(dispatch_get_main_queue(), ^{
           [self->interstitialAdsFactory showAdFromRootViewController:RCTPresentedViewController() animated:YES];
       });
       
   }
    [self sendEventWithBody:EVENT_LOADED_AD ];

}

-(void)adsAdapterInterstitialDisappear:(MNGAdsAdapter *)adsAdapter{
//    NSLog(@"adsAdapterInterstitialDisappear");
    [self sendEventWithBody:EVENT_DISAPPEAR_AD];

}
-(void)adsAdapterInterstitialDidShown:(MNGAdsAdapter *)adsAdapter{
//    NSLog(@"adsAdapterInterstitialDidShown");
    [self sendEventWithBody:EVENT_DID_SHOWN_AD];


}
-(void)adsAdapter:(MNGAdsAdapter *)adsAdapter interstitialDidFailWithError:(NSError *)error{
    
    NSLog(@"interstitialDidFailWithError %@",error);
    NSString * errorBlueStack = [NSString stringWithFormat:@"onAdFailedError = %@ , code = %ld",[error localizedDescription],(long)error.code];
    [self sendEventWithName:EVENT_NAME body:@{EVENT_KEY:EVENT_AD_ERROR,EVENT_AD_MESSAGE_ERROR_KEY:errorBlueStack}];

}

-(void)adsAdapterAdWasClicked:(MNGAdsAdapter *)adsAdapter {
    [self sendEventWithBody:EVENT_AD_CLICKED];

}

- (void)cleanUpAd
{

   [interstitialAdsFactory releaseMemory];
   interstitialAdsFactory = nil;
  _showWhenLoaded = false;

}


-(void)dealloc{
    NSLog(@"dealloc");

    [self cleanUpAd];
  
}
@end
