#import "MAXMrecBannerViewController.h"
#import "AdViewDemoMacros.h"

NSString * const storedMrecImpDisplayBannerMAX = @"POSIDcsts715vz17x";
NSString * const maxAdUnitMrecBannerRendering = @"a399e70b998ab175";

@interface MAXMrecBannerViewController ()

@property (nonatomic) ADVIEW_MediationBannerAdUnit * maxAdUnit;
@property (nonatomic) AdViewMAXMediationBannerUtils * maxMediationDelegate;
@property (nonatomic) MAAdView * maxAdBannerView;

@end

@implementation MAXMrecBannerViewController

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

- (void)createAd {
    self.maxAdBannerView = [[MAAdView alloc] initWithAdUnitIdentifier:maxAdUnitMrecBannerRendering
                                                              adFormat:MAAdFormat.mrec];

    self.maxAdBannerView.frame = CGRectMake(0, 0, self.adSize.width, self.adSize.height);
    self.maxAdBannerView.delegate = self;
    [self.maxAdBannerView setHidden:NO];

    [[AdViewMAXBannerConfigIdBridge shared] registerWithAdUnitIdentifier:maxAdUnitMrecBannerRendering configId:storedMrecImpDisplayBannerMAX];

    self.bannerView.backgroundColor = [UIColor clearColor];
    [self.bannerView addSubview:self.maxAdBannerView];

    self.maxMediationDelegate = [[AdViewMAXMediationBannerUtils alloc] initWithAdView:self.maxAdBannerView];

    self.maxAdUnit = [[ADVIEW_MediationBannerAdUnit alloc] initWithConfigID:storedMrecImpDisplayBannerMAX size:self.adSize mediationDelegate:self.maxMediationDelegate];

    self.maxAdUnit.adFormat = ADVIEW_AdFormat.banner;

    @weakify(self);
    [self.maxAdUnit fetchDemandWithCompletion:^(enum ADVIEW_ResultCode resultCode) {
        @strongify(self);
        if (!self) { return; }

        [self.maxAdBannerView loadAd];
    }];
}

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

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

    NSError * maxError = [[NSError alloc] initWithDomain:@"MAX" code:error.code userInfo:@{NSLocalizedDescriptionKey: error.message}];
    [self.maxAdUnit adObjectDidFailToLoadAdWithAdObject:self.maxAdBannerView with:maxError];
}

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

    NSError * maxError = [[NSError alloc] initWithDomain:@"MAX" code:error.code userInfo:@{NSLocalizedDescriptionKey: error.message}];
    [self.maxAdUnit adObjectDidFailToLoadAdWithAdObject:self.maxAdBannerView with:maxError];
}

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

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

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

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

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

@end
