#import "InterstitialHandler.h"
#import "NexverseAdBridge.h"
@import Nexverse;

@interface InterstitialHandler ()
@property (nonatomic, strong) InterstitialRenderingAdUnit *interstitialView;

@end

@implementation InterstitialHandler

- (void)load:(NSString *)configId format:(int)format
{
    self.interstitialView = [[InterstitialRenderingAdUnit alloc] initWithConfigID:configId bidFloor:NULL];

    AdFormat *adformat = AdFormat.banner;
    if(format == 1)
        adformat = AdFormat.video;
    
    self.interstitialView.adFormats = [[NSSet alloc] initWithObjects:adformat, nil];
    self.interstitialView.delegate = self;
    self.interstitialView.redirectionType = RedirectionTypeExternalBrowser;

    self.interstitialView.isPlaybackButtonVisible = YES;
    self.interstitialView.isMuteButtonVisible = YES;

    // 3. Load the interstitial ad
    [self.interstitialView loadAd];
}

- (void)show{
    if(self.interstitialView && self.interstitialView.isReady){
        UIViewController *rootVC = [UIApplication sharedApplication].keyWindow.rootViewController;
        [self.interstitialView showFrom:rootVC];
    }
}

// MARK: - InterstitialAdUnitDelegate
- (void)interstitialDidReceiveAd:(InterstitialRenderingAdUnit *)interstitial {
    // Show interstitial from a viewController
    [[NexverseAdBridge sharedInstance] sendEvent:@"OnInterstitialLoaded" data:@""];
}

- (void)interstitial:(InterstitialRenderingAdUnit *)interstitial didFailToReceiveAdWithError:(NSError *)error {
    // Handle ad load failure
    [[NexverseAdBridge sharedInstance] sendEvent:@"OnInterstitialFailed" data:error.description];
}

- (void)interstitial:(InterstitialRenderingAdUnit *)interstitial didFailToShowAdWithError:(NSError *)error {
    // Handle ad show failure
    [[NexverseAdBridge sharedInstance] sendEvent:@"OnInterstitialShowError" data:error.description];
}

- (void)interstitialWillPresentAd:(InterstitialRenderingAdUnit *)interstitial {
    // Handle ad presentation
    [[NexverseAdBridge sharedInstance] sendEvent:@"OnInterstitialDisplayed" data:@""];
}

- (void)interstitialDidDismissAd:(InterstitialRenderingAdUnit *)interstitial {
    // Handle ad dismissal
    [[NexverseAdBridge sharedInstance] sendEvent:@"OnInterstitialClosed" data:@""];
}

- (void)interstitialWillLeaveApplication:(InterstitialRenderingAdUnit *)interstitial {
    // Handle app leaving foreground
}

- (void)interstitialDidClickAd:(InterstitialRenderingAdUnit *)interstitial {
    // Handle ad click
    [[NexverseAdBridge sharedInstance] sendEvent:@"OnInterstitialClicked" data:@""];
}
@end
