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

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

@interface BluestackBannerView () <MNGAdsAdapterBannerDelegate,MNGAdsAdapterRefreshDelegate,MNGClickDelegate>{
    MNGAdsSDKFactory *bannerAdsFactory;
    UIView *_adView;
}
@end

@implementation BluestackBannerView

- (instancetype)init
{
   self = [super init];
   if (self != nil)
   {
       bannerAdsFactory = [[MNGAdsSDKFactory alloc]init];
   }
   return self;
}

- (void)didSetProps:(NSArray<NSString *> *)changedProps {    
    if ([changedProps containsObject:@"shouldLoadNow"] && _shouldLoadNow) {
        [self loadBanner: _preference];
    }else if (_propsChanged) {
        [self createViewIfCan];
    }
    _propsChanged = false;
}

-(void)setHeight:(CGFloat)height{
    // NSLog(@"BluestackBannerView setHeight: %f",height);
    _height = height;
    _propsChanged = true;
}

-(void)setWidth:(CGFloat)width{
    // NSLog(@"BluestackBannerView setWidth: %f",width);
    _width = width;
    _propsChanged = true;
}

- (void)setPlacementId:(NSString *)placementId
{
    // NSLog(@"BluestackBannerView setPlacementId: %@",placementId);
    _placementId = placementId;
    _propsChanged = true;
}

- (void)setPreference:(NSString *)preference
{
    // NSLog(@"BluestackBannerView setPreference: %@",preference);
    _preference = preference;
    _propsChanged = true;
}

-(void)setShouldLoadWhenReady:(BOOL)shouldLoadWhenReady{
    _shouldLoadWhenReady  = shouldLoadWhenReady;
    _propsChanged = true;
}

-(void)setShouldLoadNow:(BOOL)shouldLoadNow{
    _shouldLoadNow  = shouldLoadNow;
}

- (void)loadBanner:(NSString *)preferenceJSON {
    // NSLog(@"BluestackBannerView loadBanner");
    
    if (_onAdLoadCalled) {
        _onAdLoadCalled(nil);
    }
    
    if (![MNGAdsSDKFactory isInitialized]){
        if (_onAdFailedToLoad) {
            _onAdFailedToLoad(RCTMakeError(@"SDK is not initialized", nil, nil));
        } else {
            RCTMakeAndLogError(@"SDK is not initialized", nil, nil);
        }
        return;
    }
    
    if (![self IsBannerAdsFactoryAvailable]){
        if (_onAdFailedToLoad) {
            _onAdFailedToLoad(RCTMakeError(@"SDK is busy processing a request", nil, nil));
        } else {
            RCTMakeAndLogError(@"SDK is busy processing a request", nil, nil);
        }
        return;
    }
    
    if (_adView) {
        [_adView removeFromSuperview];
    }
    
    bannerAdsFactory.bannerDelegate = self;
    bannerAdsFactory.refreshDelegate = self;
    bannerAdsFactory.clickDelegate = self;
    
    bannerAdsFactory.viewController = RCTPresentedViewController();
    bannerAdsFactory.placementId = _placementId;
//    NSLog(@"BluestackBannerView_height %f",_height);
    MNGAdSize size = CGRectMake(0, 0, _width, _height);
//    MNGPreference *preferences =  [[MNGPreference alloc]init];
    MNGPreference *preferences = [BluestackAdsCommon getMNGPreference:preferenceJSON];
        
    [bannerAdsFactory loadBannerInFrame:size withPreferences:preferences];
}

// Initialise BannerAdView as soon as all the props are set
- (void)createViewIfCan{
    if (_placementId  && _preference && _height > 0 && _width > -1 && _shouldLoadWhenReady ) {
        [self loadBanner: _preference];
    }
}

-(void)create:(NSString *)preference{
    [self setPreference: preference];
    // loadBanner is now called from the didSetProps based on shouldLoadNow prop, to wait till all the props are updated
}

-(void)destroy{
    if (bannerAdsFactory != nil){
        [self destroyBanner];
    }
}

-(void)refresh:(BOOL)state{
    // NSLog(@"BluestackBannerView refresh: %i", state);
    if ([self IsBannerAdsFactoryAvailable]){
        [bannerAdsFactory toggleRefresh: state];
    }
}

- (BOOL)IsBannerAdsFactoryAvailable{
    if (bannerAdsFactory != nil && !bannerAdsFactory.isBusy){
        return true;
    }else{
        return false;
    }
}

- (void)destroyBanner {
    // NSLog(@"BluestackBannerView destroyBanner");
    [self removeBannerView];
    [bannerAdsFactory releaseMemory];
}

- (void)removeBannerView {
    // NSLog(@"BluestackBannerView removeBannerView");
    if (_adView == nil) {
        return;
    }
    [_adView removeFromSuperview];
    _adView = nil;
}


#pragma mark - MNGAdsAdapterBannerDelegate

-(void)adsAdapter:(MNGAdsAdapter *)adsAdapter bannerDidLoad:(UIView *)adView preferredHeight:(CGFloat)preferredHeight{
    // NSLog(@"BluestackBannerView adsAdapterBannerDidLoad");

    _adView = adView;
    _height = preferredHeight ;
    [self addSubview:_adView];
    
    if (_onAdLoaded) {
        _onAdLoaded(@{@"size":[NSNumber numberWithFloat:_height]});
    }
}

-(void)adsAdapter:(MNGAdsAdapter *)adsAdapter bannerDidFailWithError:(NSError *)error{
    NSLog(@"BluestackBannerView bannerDidFailWithError: %@", error.localizedDescription);
    
    if (_onAdFailedToLoad) {
        _onAdFailedToLoad(RCTJSErrorFromNSError(error));
    } else {
        RCTMakeAndLogError(error.localizedDescription, nil, error.userInfo);
    }
    if (_adView) {
      [_adView removeFromSuperview];
    }
}

-(void)adsAdapterBannerDidRefresh:(MNGAdsAdapter *)adsAdapter{
    // NSLog(@"BluestackBannerView adsAdapterBannerDidRefresh");
    if (_onAdRefreshed) {
      _onAdRefreshed(nil);
    }

}
-(void)adsAdapter:(MNGAdsAdapter *)adsAdapter bannerDidFailToRefreshWithError:(NSError *)error{
    NSLog(@"BluestackBannerView bannerDidFailToRefreshWithError: %@", error.localizedDescription);

    if (_onAdFailedToRefresh) {
      _onAdFailedToRefresh(RCTJSErrorFromNSError(error));
    } else {
      RCTMakeAndLogError(error.localizedDescription, nil, error.userInfo);
    }
}

-(void)adsAdapterAdWasClicked:(MNGAdsAdapter *)adsAdapter {
    // NSLog(@"BluestackBannerView adsAdapterAdWasClicked");
    if (_onAdClicked) {
        _onAdClicked(nil);
    }
    
}
-(void)dealloc {
    if (bannerAdsFactory == nil) {
        return;
    }
    [bannerAdsFactory releaseMemory];
    bannerAdsFactory = nil;

}
@end
