//
//  AdViewCustomEventBanner.m
//  AdViewSDKDemo
//
//  Created by hupan on 2022/3/7.
//  Copyright © 2022 AdView. All rights reserved.
//

#import "AdViewCustomEventBanner.h"
#import <AdViewSDK/AdViewSDK.h>
#import <GoogleMobileAds/GoogleMobileAds.h>
#include <stdatomic.h>

@interface AdViewCustomEventBanner ()< AdViewViewDelegate,GADMediationBannerAd,GADMediationAdapter>

@property (nonatomic, strong) AdViewView *banner;

@property (nonatomic, copy) NSString *appID;

@property (nonatomic, copy) NSString *positionId;

@property (nonatomic, copy, nullable) GADMediationBannerLoadCompletionHandler loadCompletionHandler;

@property (nonatomic, weak, nullable) id<GADMediationBannerAdEventDelegate> adEventDelegate;

@end

@implementation AdViewCustomEventBanner
{
    
    GADMediationBannerAdConfiguration *_adConfiguration;
}

#pragma mark GADMediationAdapter implementation

+ (GADVersionNumber)adSDKVersion {

    NSArray *versionComponents = [[AdViewView sdkVersion] componentsSeparatedByString:@"."];
    GADVersionNumber version = {0};
    if (versionComponents.count >= 3) {
      version.majorVersion = [versionComponents[0] integerValue];
      version.minorVersion = [versionComponents[1] integerValue];
      version.patchVersion = [versionComponents[2] integerValue];
    }
    return version;
}

+ (GADVersionNumber)adapterVersion {
    NSArray *versionComponents = [[AdViewView sdkVersion] componentsSeparatedByString:@"."];
    GADVersionNumber version = {0};
    if (versionComponents.count >= 3) {
      version.majorVersion = [versionComponents[0] integerValue];
      version.minorVersion = [versionComponents[1] integerValue];
      version.patchVersion = [versionComponents[2] integerValue];
    }
    return version;

}

+ (nullable Class<GADAdNetworkExtras>)networkExtrasClass {
    return Nil;
}

+ (void)setUpWithConfiguration:(GADMediationServerConfiguration *)configuration
             completionHandler:(GADMediationAdapterSetUpCompletionBlock)completionHandler {
    
  // This is where you you will initialize the SDK that this custom event is built for.
  // Upon finishing the SDK initialization, call the completion handler with success.
    
  completionHandler(nil);
}

-(void)loadBannerForAdConfiguration:(GADMediationBannerAdConfiguration *)adConfiguration
                   completionHandler:(GADMediationBannerLoadCompletionHandler)completionHandler {

    __block atomic_flag completionHandlerCalled = ATOMIC_FLAG_INIT;
    __block GADMediationBannerLoadCompletionHandler originalCompletionHandler =
        [completionHandler copy];

    _loadCompletionHandler = ^id<GADMediationBannerAdEventDelegate>(
        _Nullable id<GADMediationBannerAd> ad, NSError *_Nullable error) {
      // Only allow completion handler to be called once.
      if (atomic_flag_test_and_set(&completionHandlerCalled)) {
        return nil;
      }

      id<GADMediationBannerAdEventDelegate> delegate = nil;
      if (originalCompletionHandler) {
        // Call original handler and hold on to its return value.
        delegate = originalCompletionHandler(ad, error);
      }

      // Release reference to handler. Objects retained by the handler will also be released.
      originalCompletionHandler = nil;

      return delegate;
    };
    if (![self checkAppParameter:adConfiguration.credentials.settings[@"parameter"]]) {
        return;
    }
   
    _adConfiguration = adConfiguration;
    AdViewBannerSize bannerSize = [self AdViewBannerAdSizeFromRequestedSize:adConfiguration.adSize];
    self.banner = [AdViewView requestBannerSize:bannerSize
                                     bannerType:AdViewBannerType_normal
                                     positionId:self.positionId
                                       delegate:self];

    
}


- (BOOL)checkAppParameter:(NSString *)parameter{
    if (parameter && ![parameter isEqualToString:@""]) {
        NSArray *array = [parameter componentsSeparatedByString:@";"];
        self.appID = array.firstObject;
        self.positionId = array.lastObject;
        return YES;
    }
    NSString *errorMessage = @"parameter can not be extracted. Please check your configuration on AdMob dashboard.";
    NSDictionary *userInfo = @{ NSLocalizedDescriptionKey : errorMessage };
    NSError *error = [NSError errorWithDomain:NSStringFromClass([self class]) code:0 userInfo:userInfo];
    self.adEventDelegate = _loadCompletionHandler(nil, error);

    return NO;
}


- (AdViewBannerSize)AdViewBannerAdSizeFromRequestedSize:(GADAdSize)requestedSize
{
    CGSize requestAdSize = requestedSize.size;

    if ((int)(requestAdSize.height) >= 250 && (int)(requestAdSize.width) >= 300){
        return AdViewBannerSize_300x250;
    }else if ((int)(requestAdSize.height) >= 90 && (int)(requestAdSize.width) >= 728) {
        return AdViewBannerSize_728x90;
    } else if ((int)(requestAdSize.height) >= 60 && (int)(requestAdSize.width) >= 480){
        return AdViewBannerSize_480x60;
    } else if ((int)(requestAdSize.height) >= 44 && (int)(requestAdSize.width) >= 480){
        return AdViewBannerSize_480x44;
    } else {
        return AdViewBannerSize_320x50;
    }
}

#pragma mark AdViewDelegate implementation
- (NSString *)appId {
    
    return self.appID;
}

- (UIViewController *)viewControllerForShowModal {
    
    return _adConfiguration.topViewController;

}

- (int)autoRefreshInterval{
    
    return 0;
}

- (void)didReceivedAd:(AdViewView *)adView {

    self.adEventDelegate = _loadCompletionHandler(self, nil);
}

- (void)didFailToReceiveAd:(AdViewView *)adView Error:(NSError *)error {

    self.adEventDelegate = _loadCompletionHandler(nil, error);
}

- (void)adViewDidDisplayAd:(AdViewView *)adView {
    
    [self.adEventDelegate reportImpression];
}

- (void)adViewWillPresentScreen:(AdViewView *)adView{

    [self.adEventDelegate reportClick];
    [self.adEventDelegate willPresentFullScreenView];
}

- (void)adViewDidDismissScreen:(AdViewView *)adView {
    
    [self.adEventDelegate didDismissFullScreenView];
    
}

- (BOOL)logMode {
    
    return YES;
}

#pragma mark GADMediationBannerAd implementation

- (nonnull UIView *)view {
    
  return self.banner;
    
}

@end
