#import "RCTAppNexusBannerView.h"

#if __has_include(<React/RCTBridgeModule.h>)
#import <React/RCTBridgeModule.h>
#import <React/UIView+React.h>
#import <React/RCTLog.h>
#else
#import "RCTBridgeModule.h"
#import "UIView+React.h"
#import "RCTLog.h"
#endif


@implementation RCTAppNexusBannerView
{
    ANBannerAdView *_bannerView;
}

- (void)didSetProps:(NSArray<NSString *> *)changedProps
{
    BOOL reloadAdView = NO;

    if ([changedProps containsObject:@"placementId"]) {
        [self recreateAdView: _placementId];
        reloadAdView = YES;
    }

	if ([changedProps containsObject:@"sizes"] ||
		[changedProps containsObject:@"autoRefreshInterval"] ||
		[changedProps containsObject:@"keywords"] ||
    [changedProps containsObject:@"shouldResizeAdToFitContainer"]) {
        reloadAdView = YES;
    }

    if (reloadAdView) {
        _bannerView.adSizes = [self toCGSizes: _sizes];
        _bannerView.autoRefreshInterval = _autoRefreshInterval;
        [self addKeywords:_keywords toBanner:_bannerView];

        [_bannerView loadAd];
	}
}

-(void)recreateAdView:(NSString *)placementId
{
    if (_bannerView) {
        [_bannerView removeFromSuperview];
    }

    _bannerView = [ANBannerAdView adViewWithFrame:self.bounds placementId:_placementId];
    _bannerView.translatesAutoresizingMaskIntoConstraints = NO;
    _bannerView.delegate = self;
    _bannerView.rootViewController = [UIApplication sharedApplication].keyWindow.rootViewController;

    [self addSubview:_bannerView];
    
    [_bannerView.leftAnchor constraintEqualToAnchor:self.leftAnchor].active = YES;
    [_bannerView.rightAnchor constraintEqualToAnchor:self.rightAnchor].active = YES;
    [_bannerView.topAnchor constraintEqualToAnchor:self.topAnchor].active = YES;
    [_bannerView.bottomAnchor constraintEqualToAnchor:self.bottomAnchor].active = YES;
}

- (void)adDidReceiveAd:(id)ad
{
    CGSize actualSize = _bannerView.loadedAdSize;
    
    if (_onAdLoadSuccess) {
        _onAdLoadSuccess(@{
                           @"width": [NSNumber numberWithUnsignedInt:actualSize.width],
                           @"height": [NSNumber numberWithUnsignedInt:actualSize.height],
                           });
    }
}

- (void)ad:(id)ad requestFailedWithError:(NSError *)error
{
    if (_onAdLoadFail) {
        _onAdLoadFail(@{@"error": error});
    }
}

- (NSArray *)toCGSizes:(NSArray *)sizes
{
    NSMutableArray *adSizes = [NSMutableArray array];

    for (int i = 0; i < [sizes count]; i++) {
        CGSize size = CGSizeMake([sizes[i][0] doubleValue], [sizes[i][1] doubleValue]);
        [adSizes addObject:[NSValue valueWithCGSize:size]];
    }

    return adSizes;
}

- (void)addKeywords:(NSDictionary *)keywords toBanner:(ANBannerAdView *)bannerView
{
    NSArray *keywordKeys = [keywords allKeys];
    for (NSString *key in keywordKeys) {
        [bannerView addCustomKeywordWithKey:key value:keywords[key]];
    }
}

@end
