//
//  AdViewCustomEventNative.m
//  admobTest
//
//  Created by hupan on 2022/3/15.
//

#import "AdViewCustomEventNative.h"
#import <AdViewSDK/AdViewSDK.h>
#import "AdViewMediatedNativeAd.h"
#include <stdatomic.h>

@interface AdViewCustomEventNative()<AdViewNativeAdDelegate, GADNativeAdLoaderDelegate,GADMediationAdapter>

@property (nonatomic, strong) AdViewNativeAd * native;

@property (nonatomic, copy) NSString *appID;

@property (nonatomic, copy) NSString *positionId;

@property (nonatomic, assign) int adCount;

@property (nonatomic, strong) AdViewMediatedNativeAd *mediatedAd;

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

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





@end

@implementation AdViewCustomEventNative



- (BOOL)checkAppParameter:(NSString *)parameter{
    if (parameter && ![parameter isEqualToString:@""]) {
        NSArray *array = [parameter componentsSeparatedByString:@";"];
        self.appID = array.firstObject;
        self.positionId = array.lastObject;
        return YES;
    }
    
    
    return NO;
}

- (BOOL)handlesUserClicks
{
    return NO;
}

- (BOOL)handlesUserImpressions
{
    return NO;
}


#pragma mark AdViewNativeDelegate implementation
/*
 *
 */
- (void)adViewNativeAdSuccessToLoadAd:(AdViewNativeAd *)adViewNativeAd NativeData:(NSArray <AdViewNativeData *>*)nativeDataArray{
    self.mediatedAd = [[AdViewMediatedNativeAd alloc] initWithAdViewNativeAd:adViewNativeAd NativeData:nativeDataArray];
    self.adEventDelegate = _loadCompletionHandler(self.mediatedAd, nil);
}

/*
 *
 */
- (void)adViewNativeAdFailToLoadAd:(AdViewNativeAd *)adViewNativeAd WithError:(NSError *)error{
    self.adEventDelegate = _loadCompletionHandler(nil, error);
}

/*
 *
 */
- (void)adViewNativeAdWillShowPresent{
    [GADMediatedUnifiedNativeAdNotificationSource mediatedNativeAdDidRecordClick:self.mediatedAd];
    [GADMediatedUnifiedNativeAdNotificationSource mediatedNativeAdWillPresentScreen:self.mediatedAd];
}

/*
 *
 */
- (void)adViewNativeAdClosed{
    [GADMediatedUnifiedNativeAdNotificationSource mediatedNativeAdDidDismissScreen:self.mediatedAd];
}

/*
 *
 */
- (void)adViewNativeAdResignActive{

}

- (BOOL)logMode {
    return YES;
}

- (void)adLoader:(nonnull GADAdLoader *)adLoader didFailToReceiveAdWithError:(nonnull NSError *)error {
    
}

- (void)adLoader:(nonnull GADAdLoader *)adLoader didReceiveNativeAd:(nonnull GADNativeAd *)nativeAd {
  
  
}

#pragma mark GADMediationAdapter implementation


- (void)loadNativeAdForAdConfiguration:(GADMediationNativeAdConfiguration *)adConfiguration
                     completionHandler:(GADMediationNativeLoadCompletionHandler)completionHandler {
  __block atomic_flag completionHandlerCalled = ATOMIC_FLAG_INIT;
  __block GADMediationNativeLoadCompletionHandler originalCompletionHandler =
      [completionHandler copy];

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

    id<GADMediationNativeAdEventDelegate> 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.native = [[AdViewNativeAd alloc] initWithAppKey:self.appID positionID:self.positionId];
    self.native.delegate = self;
    [self.native loadNativeAdWithCount:1];
    
}

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