#import "AdMobDisplayInterstitialViewController.h"
#import "AdViewDemoMacros.h"

NSString * const storedImpDisplayInterstitialAdMob = @"POSIDzuqwln00ml38";
NSString * const adMobAdUnitDisplayInterstitial = @"ca-app-pub-7283949697136772/3280121025";

@interface AdMobDisplayInterstitialViewController ()

// adview
@property (nonatomic) ADVIEW_MediationInterstitialAdUnit * admobAdUnit;
@property (nonatomic) AdViewAdMobMediationInterstitialUtils * mediationDelegate;

// AdMob
@property (nonatomic) GADInterstitialAd * interstitial;

@end

@implementation AdMobDisplayInterstitialViewController

- (void)loadView {
    [super loadView];
    
    [self createAd];
}

- (void)createAd {
    // 1. Create a GADRequest
    GADRequest * gadRequest = [GADRequest new];
    
    // 2. Create an AdViewAdMobMediationInterstitialUtils
    self.mediationDelegate = [[AdViewAdMobMediationInterstitialUtils alloc] initWithGadRequest:gadRequest];
    
    // 3. Create a ADVIEW_MediationInterstitialAdUnit
    self.admobAdUnit = [[ADVIEW_MediationInterstitialAdUnit alloc] initWithConfigId:storedImpDisplayInterstitialAdMob mediationDelegate:self.mediationDelegate];
    
    // 4. Make a bid request to AdView Server
    [self.admobAdUnit fetchDemandWithCompletion:^(enum ADVIEW_ResultCode resultCode) {
        @weakify(self);
        
        // 5. Load the interstitial ad
        [GADInterstitialAd loadWithAdUnitID:adMobAdUnitDisplayInterstitial request:gadRequest completionHandler:^(GADInterstitialAd * _Nullable interstitialAd, NSError * _Nullable error) {
            @strongify(self);
            if (!self) { return; }
            
            if (error != nil) {
                AdViewDemoLogError(@"%@", error.localizedDescription);
                return;
            }
            
            // 6. Present the interstitial ad
            if (interstitialAd != nil) {
                self.interstitial = interstitialAd;
                self.interstitial.fullScreenContentDelegate = self;
                [self.interstitial presentFromRootViewController:self];
            }
        }];
    }];
}

// MARK: - GADFullScreenContentDelegate

- (void)ad:(id<GADFullScreenPresentingAd>)ad didFailToPresentFullScreenContentWithError:(NSError *)error {
    AdViewDemoLogError(@"%@", error.localizedDescription);
}

@end
