#import "AdMobDisplayBannerViewController.h"
#import "AdViewDemoMacros.h"

NSString * const storedImpDisplayBannerAdMob = @"POSIDjw2dypnd7yv8";
NSString * const adMobAdUnitDisplayBannerRendering = @"ca-app-pub-7283949697136772/3397053982";

@interface AdMobDisplayBannerViewController ()

// adview
@property (nonatomic) ADVIEW_MediationBannerAdUnit * adviewAdMobMediaitonAdUnit;
@property (nonatomic) AdViewAdMobMediationBannerUtils * mediationDelegate;

// AdMob
@property (nonatomic) GADBannerView * gadBanner;

@end

@implementation AdMobDisplayBannerViewController

- (void)loadView {
    [super loadView];

    [self createAd];
}

- (void)createAd {
    // 1. Create a GADRequest
    GADRequest * gadRequest = [GADRequest new];
    [AdViewAdMobUtils setConfigIdOnRequest:storedImpDisplayBannerAdMob request:gadRequest];

    // 2. Create a GADBannerView
    self.gadBanner = [[GADBannerView alloc] initWithAdSize:GADAdSizeFromCGSize(self.adSize)];
    self.gadBanner.adUnitID = adMobAdUnitDisplayBannerRendering;
    self.gadBanner.delegate = self;
    self.gadBanner.rootViewController = self;

    // Add GMA SDK banner view to the app UI
    [self.bannerView addSubview:self.gadBanner];

    // 3. Create an AdViewAdMobMediationBannerUtils
    self.mediationDelegate = [[AdViewAdMobMediationBannerUtils alloc] initWithGadRequest:gadRequest bannerView:self.gadBanner];

    // 4. Create a ADVIEW_MediationBannerAdUnit
    self.adviewAdMobMediaitonAdUnit = [[ADVIEW_MediationBannerAdUnit alloc] initWithConfigID:storedImpDisplayBannerAdMob size:self.adSize mediationDelegate:self.mediationDelegate];

    // 5. Make a bid request to AdView Server
    @weakify(self);
    [self.adviewAdMobMediaitonAdUnit fetchDemandWithCompletion:^(enum ADVIEW_ResultCode resultCode) {
        @strongify(self);
        if (!self) { return; }

        // 6. Load ad
        [self.gadBanner loadRequest:gadRequest];
    }];
}

#pragma mark - GADBannerViewDelegate

- (void)bannerViewDidReceiveAd:(GADBannerView *)bannerView {

}

- (void)bannerView:(GADBannerView *)bannerView didFailToReceiveAdWithError:(NSError *)error {
    AdViewDemoLogError(@"%@", error.localizedDescription);

    [self.adviewAdMobMediaitonAdUnit adObjectDidFailToLoadAdWithAdObject:self.gadBanner with:error];
}

@end
