//
//  BluestackRewardedAdManager.m
//  @azerion/bluestack-sdk-react-native
//
//  Created by moin on 20/5/2024.
//

#import "BluestackRewardedAdManager.h"
#import "BluestackAdsCommon.h"
#import <React/RCTUtils.h>
#import <React/RCTLog.h>
#import <BlueStackSDK/MNGAdsSDKFactory.h>
#import <BlueStackSDK/BlueStackSDK.h>

@interface BluestackRewardedAdManager ()<MAdvertiseAdapterRewardedVideoAdDelegate>{
    MAdvertiseRewardedVideoAd *rewardedAdsFactory;
}

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

@end
@implementation BluestackRewardedAdManager{
     bool hasListeners;
}

//@synthesize bridge = _bridge;
NSString *  EVENT_LOADED_REWARDED_AD = @"onAdLoaded";
NSString *  EVENT_DISAPPEAR_REWARDED_AD = @"onAdDismissed";
NSString *  EVENT_DID_SHOWN_REWARDED_AD = @"onAdDisplayed";
NSString *  EVENT_REWARDED_AD_CLICKED = @"onAdClicked";
NSString *  EVENT_REWARDED_AD_ERROR= @"onAdFailedError";
NSString *  EVENT_REWARDED_AD_MESSAGE_ERROR_KEY= @"errorMessage";
NSString *  EVENT_REWARD_EARNED = @"onRewardEarned";
NSString *  EVENT_REWARD_TYPE_KEY = @"rewardType";
NSString *  EVENT_REWARD_AMOUNT_KEY = @"rewardAmount";

NSString * REWARDED_EVENT_KEY = @"rewardedEvent";
NSString * REWARDED_EVENT_NAME = @"RewardedAdEvent";

RCT_EXPORT_MODULE(BluestackRewardedAdManager)

RCT_EXPORT_METHOD(
    loadAd:(NSString *)placementId
    autoDisplay:(BOOL)autoDisplay
    withPreference:(NSString *)preferenceJSON
)
{  
    [self cleanUpAd];
   
    [rewardedAdsFactory releaseMemory];
    rewardedAdsFactory = [[MAdvertiseRewardedVideoAd alloc] initWithPlacementID:placementId];
    [rewardedAdsFactory setDelegate:self];
    rewardedAdsFactory.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];
    dispatch_async(dispatch_get_main_queue(), ^{
        [self->rewardedAdsFactory loadAdWithPreferences:preferences];
    });
}

RCT_EXPORT_METHOD(
 displayAd
) 
{  
    [self show];
}

- (void)show {
    
    if (self->rewardedAdsFactory && self->rewardedAdsFactory.isAdValid) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self->rewardedAdsFactory showAdFromRootViewController:RCTPresentedViewController() animated:YES];
        });
    }

    // Trigger 'onAdDisplayed' from here, because currently it's not available in MAdvertiseAdapterRewardedVideoAdDelegate
    [self sendEventWithBody:EVENT_DID_SHOWN_REWARDED_AD];
}

#pragma mark - RCTEventEmitter

- (NSArray<NSString *> *)supportedEvents {
    return @[REWARDED_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:REWARDED_EVENT_NAME body:@{REWARDED_EVENT_KEY:body}];
  }
}

#pragma mark - MAdvertiseAdapterRewardedVideoAdDelegate

-(void)adsAdapterRewardedVideoAdDidLoad:(MNGAdsAdapter *)adsAdapter{
//    NSLog(@"adsAdapterRewardedVideoAdDidLoad");
  
    if (_showWhenLoaded) {
        [self show];      
    }

    [self sendEventWithBody:EVENT_LOADED_REWARDED_AD ];
}

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

-(void)adsAdapter:(MNGAdsAdapter *)adsAdapter rewardedVideoAdDidFailWithError:(NSError *)error{
    NSLog(@"rewardedVideoAdDidFailWithError %@",error);
    NSString * errorBlueStack = [NSString stringWithFormat:@"rewardedVideoAdDidFailWithError = %@ , code = %ld",[error localizedDescription],(long)error.code];
    [self sendEventWithName:REWARDED_EVENT_NAME body:@{REWARDED_EVENT_KEY:EVENT_REWARDED_AD_ERROR,EVENT_REWARDED_AD_MESSAGE_ERROR_KEY:errorBlueStack}];
}

- (void)adsAdapterRewardedVideoAd:(MNGAdsAdapter *)adsAdapter withReward:(MAdvertiseReward *)reward {
    NSLog(@"adsAdapterRewardedVideoAd withReward: %@",reward.amount);
    [self sendEventWithName:REWARDED_EVENT_NAME body:@{REWARDED_EVENT_KEY:EVENT_REWARD_EARNED,EVENT_REWARD_TYPE_KEY:reward.type,EVENT_REWARD_AMOUNT_KEY:reward.amount}];
}

-(void)adsAdapterRewardedVideoAdDidClick:(MNGAdsAdapter *)adsAdapter {
    [self sendEventWithBody:EVENT_REWARDED_AD_CLICKED];
}

- (void)cleanUpAd
{
   [rewardedAdsFactory releaseMemory];
   rewardedAdsFactory = nil;
  _showWhenLoaded = false;
}

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

    [self cleanUpAd];
}
@end
