#import "AdMobVideoRewardedViewController.h"
#import "AdViewDemoMacros.h"

NSString * const storedImpVideoRewardedAdMob = @"POSIDxdsaplpm4ar1";
NSString * const adMobAdUnitVideoRewardedId = @"ca-app-pub-7283949697136772/4732803494";

@interface AdMobVideoRewardedViewController ()

// adview
@property (nonatomic) ADVIEW_MediationRewardedAdUnit * admobRewardedAdUnit;
@property (nonatomic) AdViewAdMobMediationRewardedUtils * mediationDelegate;

// AdMob
@property (nonatomic) GADRewardedAd * gadRewardedAd;

@end

@implementation AdMobVideoRewardedViewController

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

- (void)createAd {
    // 1. Create a GADRequest
    GADRequest * gadRequest = [GADRequest new];
    
    // 2. Create an AdViewAdMobMediationRewardedUtils
    self.mediationDelegate = [[AdViewAdMobMediationRewardedUtils alloc] initWithGadRequest:gadRequest];
    
    // 3. Create a ADVIEW_MediationRewardedAdUnit
    self.admobRewardedAdUnit = [[ADVIEW_MediationRewardedAdUnit alloc] initWithConfigId:storedImpVideoRewardedAdMob mediationDelegate:self.mediationDelegate];
    
    // 4. Make a bid request to AdView Server
    @weakify(self);
    [self.admobRewardedAdUnit fetchDemandWithCompletion:^(enum ADVIEW_ResultCode resultCode) {
        @strongify(self);
        
        // 5. Load the rewarded ad
        @weakify(self);
        [GADRewardedAd loadWithAdUnitID:adMobAdUnitVideoRewardedId
                                request:gadRequest
                      completionHandler:^(GADRewardedAd * _Nullable rewardedAd, NSError * _Nullable error) {
            @strongify(self);
            if (!self) { return; }
            
            if (error != nil) {
                AdViewDemoLogError(@"%@", error.localizedDescription);
                return;
            }
            
            // 6. Present the rewarded ad
            if (rewardedAd != nil) {
                self.gadRewardedAd = rewardedAd;
                self.gadRewardedAd.fullScreenContentDelegate = self;
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [self.gadRewardedAd presentFromRootViewController:self userDidEarnRewardHandler:^{
                        NSLog(@"User did earn reward.");
                    }];
                });
            }
        }];
    }];
}

// MARK: - GADFullScreenContentDelegate

- (void)ad:(id<GADFullScreenPresentingAd>)ad didFailToPresentFullScreenContentWithError:(NSError *)error {
    AdViewDemoLogError(@"%@", error.localizedDescription);
}

@end
