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

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

@interface AdViewCustomEventInterstitial () < AdViewViewDelegate,GADMediationAdapter,
GADMediationInterstitialAd>

@property (nonatomic, strong) AdViewView *interstitial;

@property (nonatomic, strong) UIViewController *vc;

@property (nonatomic, copy) NSString *appID;

@property (nonatomic, copy) NSString *positionId;

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

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

@end


@implementation AdViewCustomEventInterstitial




- (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 = self.loadCompletionHandler(nil, error);
    return NO;
}


#pragma mark GADMediationInterstitialAd implementation

- (void)presentFromViewController:(UIViewController *)viewController {
  
    self.vc = viewController;
    [self.interstitial showInterstitialWithRootViewController:viewController];
}

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

- (UIViewController *)viewControllerForShowModal {
    return self.vc;
}

- (void)didReceivedAd:(AdViewView *)adView {
    self.adEventDelegate = _loadCompletionHandler(self, nil);
}

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

- (void)didFailToReceiveAd:(AdViewView *)adView Error:(NSError *)error {
    self.adEventDelegate = _loadCompletionHandler(nil, error);
}

- (void)adViewWillPresentScreen:(AdViewView *)adView{
    [self.adEventDelegate willPresentFullScreenView];
    [self.adEventDelegate reportClick];
}

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

- (BOOL)logMode {
    return YES;
}


#pragma mark GADMediationAdapter implementation

- (void)loadInterstitialForAdConfiguration:
            (GADMediationInterstitialAdConfiguration *)adConfiguration
                         completionHandler:
                             (GADMediationInterstitialLoadCompletionHandler)completionHandler {
  __block atomic_flag completionHandlerCalled = ATOMIC_FLAG_INIT;
  __block GADMediationInterstitialLoadCompletionHandler originalCompletionHandler =
      [completionHandler copy];

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

    id<GADMediationInterstitialAdEventDelegate> 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;
    }
    
    self.interstitial = [AdViewView requestAdInterstitialWithPositionId:self.positionId delegate:self];
  
}


+ (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;
}

@end
