//
//  AdViewCustomEventInterstitial.m
//  AdViewSDKDemo
//
//  Created by hupan on 2022/3/9.
//  Copyright © 2022 AdView. All rights reserved.
//

#import "AdViewCustomEventInterstitial.h"
#import <GoogleMobileAds/GoogleMobileAds.h>
#import <AdViewSDK/AdViewSDK.h>

@interface AdViewCustomEventInterstitial () <GADCustomEventInterstitial, AdViewViewDelegate>

@property (nonatomic, strong) AdViewView *interstitial;

@property (nonatomic, strong) UIViewController *vc;

@property (nonatomic, copy) NSString *appID;

@property (nonatomic, copy) NSString *positionId;

@end


@implementation AdViewCustomEventInterstitial
@synthesize delegate;

- (void)requestInterstitialAdWithParameter:(NSString *)serverParameter
                                     label:(NSString *)serverLabel
                                   request:(GADCustomEventRequest *)request
{
    if (![self checkAppParameter:serverParameter]) {
        return;
    }
    
    self.interstitial = [AdViewView requestAdInterstitialWithPositionId:self.positionId delegate:self];
}

- (BOOL)checkAppParameter:(NSString *)parameter{
    if (parameter && ![parameter isEqualToString:@""]) {
        NSArray *array = [parameter componentsSeparatedByString:@";"];
        self.appID = array.firstObject;
        self.positionId = array.lastObject;
        return YES;
    }
    NSString *errorMessage = @"parameter can not be extracted. Please check your configuration on AdMob dashboard.";
    NSDictionary *userInfo = @{ NSLocalizedDescriptionKey : errorMessage };
    NSError *error = [NSError errorWithDomain:NSStringFromClass([self class]) code:0 userInfo:userInfo];
    [self.delegate customEventInterstitial:self didFailAd:error];
    return NO;
}

- (void)presentFromRootViewController:(UIViewController *)rootViewController
{
    self.vc = rootViewController;
    [self.interstitial showInterstitialWithRootViewController:rootViewController];
}


#pragma mark AdViewDelegate implementation
- (NSString *)appId {
    return self.appID;
}

- (UIViewController *)viewControllerForShowModal {
    return self.vc;
}

- (void)didReceivedAd:(AdViewView *)adView {
    [self.delegate customEventInterstitialDidReceiveAd:self];
}

- (void)didFailToReceiveAd:(AdViewView *)adView Error:(NSError *)error {
    [self.delegate customEventInterstitial:self didFailAd:error];
}

- (void)adViewWillPresentScreen:(AdViewView *)adView{
    [self.delegate customEventInterstitialWillPresent:self];
    [self.delegate customEventInterstitialWasClicked:self];
}

- (void)adViewDidDismissScreen:(AdViewView *)adView{
    [self.delegate customEventInterstitialDidDismiss:self];
}

- (BOOL)logMode {
    return YES;
}

@end
