#import "MAXDisplayRewardedViewController.h"
#import "AdViewDemoMacros.h"

NSString * const storedImpDisplayRewardedMAX = @"POSIDxdsaplpm4ar1";
NSString * const maxAdUnitDisplayRewardedId = @"b94740e7df6f86d5";

@interface MAXDisplayRewardedViewController ()

// adview
@property (nonatomic) ADVIEW_MediationRewardedAdUnit * maxRewardedAdUnit;
@property (nonatomic) AdViewMAXMediationRewardedUtils * mediationDelegate;

// MAX
@property (nonatomic) MARewardedAd * maxRewarded;

@end

@implementation MAXDisplayRewardedViewController

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

- (void)createAd {
    // 1. Create a MARewardedAd
    self.maxRewarded = [MARewardedAd sharedWithAdUnitIdentifier:maxAdUnitDisplayRewardedId];
    
    // 2. Create a AdViewMAXMediationRewardedUtils
    self.mediationDelegate = [[AdViewMAXMediationRewardedUtils alloc] initWithRewardedAd:self.maxRewarded];
    
    // 3. Create a ADVIEW_MediationRewardedAdUnit
    self.maxRewardedAdUnit = [[ADVIEW_MediationRewardedAdUnit alloc] initWithConfigId:storedImpDisplayRewardedMAX
                                                             mediationDelegate:self.mediationDelegate];
    
    // 4. Make a bid request to AdView Server
    @weakify(self);
    [self.maxRewardedAdUnit fetchDemandWithCompletion:^(enum ADVIEW_ResultCode resultCode) {
        @strongify(self);
        if (!self) { return; }
        
        // 5. Load the rewarded ad
        self.maxRewarded.delegate = self;
        [self.maxRewarded loadAd];
    }];
}

// MARK: - MARewardedAdDelegate

- (void)didLoadAd:(MAAd *)ad {
    if (self.maxRewarded != nil && self.maxRewarded.isReady) {
        [self.maxRewarded 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 {
}

- (void)didRewardUserForAd:(MAAd *)ad withReward:(MAReward *)reward {
    NSLog(@"User did earn reward: label - %@, amount - %ld", reward.label, reward.amount);
}

@end
