#import "AdMobVideoInterstitialViewController.h"
#import "AdViewDemoMacros.h"

NSString * const storedImpVideoInterstitialAdMob = @"POSIDxdsaplpm4ar1";
NSString * const adMobAdUnitVideoInterstitialRendering = @"ca-app-pub-7283949697136772/3280121025";

@interface AdMobVideoInterstitialViewController ()

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

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

@end

@implementation AdMobVideoInterstitialViewController

- (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:storedImpVideoInterstitialAdMob mediationDelegate:self.mediationDelegate];
    
    // 4. Set ad format
    self.admobAdUnit.adFormats = [NSSet setWithObject:ADVIEW_AdFormat.video];
    
    // 5. Make a bid request to AdView Server
    [self.admobAdUnit fetchDemandWithCompletion:^(enum ADVIEW_ResultCode resultCode) {
        @weakify(self);
        
        // 6. Load the interstitial ad
        [GADInterstitialAd loadWithAdUnitID:adMobAdUnitVideoInterstitialRendering request:gadRequest completionHandler:^(GADInterstitialAd * _Nullable interstitialAd, NSError * _Nullable error) {
            @strongify(self);
            if (!self) { return; }
            
            if (error != nil) {
                AdViewDemoLogError(@"%@", error.localizedDescription);
                return;
            }
            
            // 7. 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
