#import "MAXVideoInterstitialViewController.h"
#import "AdViewDemoMacros.h"

NSString * const storedImpVideoInterstitialMAX = @"POSIDxdsaplpm4ar1";
NSString * const maxAdUnitVideoInterstitial = @"d50565fd22a74074";

@interface MAXVideoInterstitialViewController ()

// adview
@property (nonatomic) ADVIEW_MediationInterstitialAdUnit * maxAdUnit;
@property (nonatomic) AdViewMAXMediationInterstitialUtils * maxMediationDelegate;

// MAX
@property (nonatomic) MAInterstitialAd * maxInterstitial;

@end

@implementation MAXVideoInterstitialViewController

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

- (void)createAd {
    // 1. Create a MAInterstitialAd
    self.maxInterstitial = [[MAInterstitialAd alloc] initWithAdUnitIdentifier:maxAdUnitVideoInterstitial];
    
    // 2. Create a AdViewMAXMediationInterstitialUtils
    self.maxMediationDelegate = [[AdViewMAXMediationInterstitialUtils alloc] initWithInterstitialAd:self.maxInterstitial];
    
    // 3. Create a ADVIEW_MediationInterstitialAdUnit
    self.maxAdUnit = [[ADVIEW_MediationInterstitialAdUnit alloc] initWithConfigId:storedImpVideoInterstitialMAX mediationDelegate:self.maxMediationDelegate];
    self.maxAdUnit.adFormats = [[NSSet alloc] initWithObjects:ADVIEW_AdFormat.video, nil];
    
    // 4. Make a bid request to AdView Server
    @weakify(self);
    [self.maxAdUnit fetchDemandWithCompletion:^(enum ADVIEW_ResultCode resultCode) {
        @strongify(self); 
        if (!self) { return; }
        
        // 5. Load the interstitial ad
        self.maxInterstitial.delegate = self;
        [self.maxInterstitial loadAd];
    }];
}

// MARK: - MAAdDelegate

- (void)didLoadAd:(MAAd *)ad {
    if (self.maxInterstitial != nil && self.maxInterstitial.isReady) {
        [self.maxInterstitial showAd];
    }
}

- (void)didFailToDisplayAd:(MAAd *)ad withError:(MAError *)error {
    AdViewDemoLogError(@"%@", error.message);
}

- (void)didFailToLoadAdForAdUnitIdentifier:(NSString *)adUnitIdentifier withError:(MAError *)error {
    AdViewDemoLogError(@"%@", error.message);
}

- (void)didDisplayAd:(MAAd *)ad {
}

- (void)didHideAd:(MAAd *)ad {
}

- (void)didClickAd:(MAAd *)ad {
}

@end
