#import "IronSourceC.h"
#import <Cordova/CDVViewController.h>

//** Properties **//
BOOL isBanner = true;
BOOL isInterstitial = true;
BOOL isRewardedVideo = true;
BOOL isOfferwall = true;

//** State **//
BOOL isBannerLoaded = false;
BOOL isBannerShowing = false;

//** Hidden State **//
BOOL isInitialized = false;
BOOL bannerTop = false;
BOOL bannerOverlap = true;
BOOL bannerAutoShow = false;

//** Constants **//
#define FALLBACK_USER_ID @"demoapp"

//** Constants: Events **//
static NSString *const EVENT_INITIALIZATION = @"initializationCompleted";

static NSString *const EVENT_REWARDED_VIDEO_OPENED = @"rewardedVideoOpened";
static NSString *const EVENT_REWARDED_VIDEO_CLOSED = @"rewardedVideoClosed";
static NSString *const EVENT_REWARDED_VIDEO_AVAILABILITY_CHANGED = @"rewardedVideoAvailabilityChanged";
static NSString *const EVENT_REWARDED_VIDEO_REWARDED = @"rewardedVideoRewardReceived";
static NSString *const EVENT_REWARDED_VIDEO_FAILED = @"rewardedVideoFailed";
static NSString *const EVENT_REWARDED_VIDEO_CLICKED = @"rewardedVideoClicked";
static NSString *const EVENT_REWARDED_VIDEO_STARTED = @"rewardedVideoStarted";
static NSString *const EVENT_REWARDED_VIDEO_ENDED = @"rewardedVideoEnded";

static NSString *const EVENT_INTERSTITIAL_READY = @"interstitialReady";
static NSString *const EVENT_INTERSTITIAL_LOAD_FAILED = @"interstitialLoadFailed";
static NSString *const EVENT_INTERSTITIAL_OPENED = @"interstitialOpened";
static NSString *const EVENT_INTERSTITIAL_CLOSED = @"interstitialClosed";
static NSString *const EVENT_INTERSTITIAL_SHOW_SUCCEEDED = @"interstitialShowSucceeded";
static NSString *const EVENT_INTERSTITIAL_SHOW_FAILED = @"interstitialShowFailed";
static NSString *const EVENT_INTERSTITIAL_CLICKED = @"interstitialClicked";

static NSString *const EVENT_BANNER_LOADED = @"bannerLoaded";
static NSString *const EVENT_BANNER_FAILED_TO_LOAD = @"bannerLoadFailed";
static NSString *const EVENT_BANNER_CLICKED = @"bannerClicked";
static NSString *const EVENT_BANNER_SCREEN_PRESENTED = @"bannerScreenPresented";
static NSString *const EVENT_BANNER_SCREEN_DISMISSED = @"bannerScreenDismissed";
static NSString *const EVENT_BANNER_LEFT_APPLICATION = @"bannerLeftApplication";

static NSString *const EVENT_OFFERWALL_AVAILABILITY_CHANGED = @"offerwallAvailabilityChanged";
static NSString *const EVENT_OFFERWALL_OPENED = @"offerwallOpened";
static NSString *const EVENT_OFFERWALL_SHOW_FAILED = @"offerwallShowFailed";
static NSString *const EVENT_OFFERWALL_CREDITED = @"offerwallCredited";
static NSString *const EVENT_OFFERWALL_CREDITS_FAILED = @"offerwallCreditsFailed";
static NSString *const EVENT_OFFERWALL_CLOSED = @"offerwallClosed";

static NSString *const EVENT_SEGMENT_RECEIVED = @"segmentReceived";


@implementation IronSourceC

#pragma mark - Settings

- (void) validateIntegration:(CDVInvokedUrlCommand *)command
{
    // [ISIntegrationHelper validateIntegration];
    
    // Send callback successfull
    CDVPluginResult *result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsArray:command.arguments];
    [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
}

- (void) setMode:(CDVInvokedUrlCommand *)command
{
    NSDictionary *mode = [command argumentAtIndex:0];
    
    isRewardedVideo = [[mode valueForKey:@"reward"] boolValue];
    isInterstitial = [[mode valueForKey:@"interstitial"] boolValue];
    isOfferwall = [[mode valueForKey:@"offerwall"] boolValue];
    isBanner = [[mode valueForKey:@"banner"] boolValue];
    
    // Send callback successfull
    CDVPluginResult *result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsArray:command.arguments];
    [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
}

- (void)initialize:(CDVInvokedUrlCommand *)command
{
    NSString *appKey = [command argumentAtIndex:0];
    NSNumber *userIdType = [command argumentAtIndex:2]; // Enum: [Advertising, IronSource, Specify]
    NSString *userId = [command argumentAtIndex:1] == nil ? @"" : [command argumentAtIndex:1];

    const BOOL isAdvertisingId = [userIdType isEqual:@0];
    const BOOL isSpecified = [userIdType isEqual:@2];

    //** User Id **//

    // We're using an advertisingId as the user id.
    if (isAdvertisingId)
    {
        NSString *advertisingId = [IronSource advertiserId];

        if ([advertisingId length] == 0)
        {
            userId = @"";
            NSLog(@"The built-in IronSource user id generator has been used.");
        }
        else
        {
            userId = advertisingId;
            NSLog(@"The user's advertising id has been used.");
        }
    }
    // We're using the specified user id.
    else if (isSpecified)
    {
        if ([userId length] == 0)
        {
            userId = @"";
            NSLog(@"The built-in IronSource user id generator has been used.");
        }
        else
        {
            NSLog(@"The specified user id has been used.");
        }
    }
    // We're using the built-in IronSource user id generator.
    else
    {
        userId = @"";
        NSLog(@"The built-in IronSource user id generator has been used.");
    }
    
    // Set the user id, if not blank.
    if (!([userId length] == 0)) { [IronSource setUserId:userId]; }

    //** Initialization **//

    // // Mediation Testing
    // [IronSource setAdaptersDebug:YES];

    // [Reminder] We shouldn't support automatically detecting ad-units from the IronSource console
    //            since we activate features based on the plugin toggles.
    //            This is because the IronSource SDK doesn't have a way to retrieve which toggles
    //            are set in the IronSource Console.
    
    // Ad-unit checks
    if (isRewardedVideo)
    {
        [IronSource initWithAppKey:appKey adUnits:@[IS_REWARDED_VIDEO]];
        
        [IronSource setRewardedVideoDelegate:self];
    }
    if (isInterstitial)
    {
        [IronSource initWithAppKey:appKey adUnits:@[IS_INTERSTITIAL]];
        
        [IronSource setInterstitialDelegate:self];
    }
    if (isBanner)
    {
        [IronSource initWithAppKey:appKey adUnits:@[IS_BANNER]];
        
        [IronSource setBannerDelegate:self];
        
        self.bannerController = [[UIViewController alloc] init];
        [self.bannerController.view setHidden:YES];
    }
    if (isOfferwall)
    {
        [IronSource initWithAppKey:appKey adUnits:@[IS_OFFERWALL]];

        [IronSource setOfferwallDelegate:self];
    }

    // After setting the delegates you can go ahead and initialize the SDK.

    // If all ad-units are deactivated.
    if (!isRewardedVideo && !isInterstitial && !isBanner && !isOfferwall)
    {
        // Initialize immediately.
        isInitialized = true;
        // Even if the IronSource SDK didn't truly initialize, just fake fire 
        // initialization because there is no ad-unit selected.
        [self fireEventTrigger:EVENT_INITIALIZATION];
    }
    // If any ad-unit is activated.
    else
    {
        [IronSource initWithAppKey:appKey delegate:self];
    }
    
    [IronSource setSegmentDelegate:self];

    // Send callback successfull
    CDVPluginResult *result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsArray:command.arguments];
    [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
}

#pragma mark - Advanced Settings

- (void) setConsent:(CDVInvokedUrlCommand *)command
{
    BOOL isGiven = [[command argumentAtIndex:0] boolValue];
    
    [IronSource setConsent:isGiven];
    
    CDVPluginResult *result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsArray:command.arguments];
    [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
}

- (void) setCompliance:(CDVInvokedUrlCommand *)command
{
    BOOL toggle = [[command argumentAtIndex:0] boolValue];
    
    NSString *toggleStr = (toggle ? @"YES" : @"NO");

    [IronSource setMetaDataWithKey:@"do_not_sell" value:toggleStr];
    
    CDVPluginResult *result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsArray:command.arguments];
    [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
}

- (void) setChildDirected:(CDVInvokedUrlCommand *)command
{
    BOOL toggle = [[command argumentAtIndex:0] boolValue];
    
    NSString *toggleStr = (toggle ? @"YES" : @"NO");

    [IronSource setMetaDataWithKey:@"is_child_directed" value:toggleStr];
    
    CDVPluginResult *result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsArray:command.arguments];
    [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
}

- (void) setDeviceIdOptOut:(CDVInvokedUrlCommand *)command
{
    // BOOL toggle = [[command argumentAtIndex:0] boolValue];
    
    // NSString *toggleStr = (toggle ? @"YES" : @"NO");

    // [IronSource setMetaDataWithKey:@"is_deviceid_optout" value:toggleStr];
    
    CDVPluginResult *result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsArray:command.arguments];
    [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
}

- (void) setMetaData:(CDVInvokedUrlCommand *)command
{
    NSString *key = [command argumentAtIndex:0];
    NSString *data = [command argumentAtIndex:1];

    [IronSource setMetaDataWithKey:key value:data];
    
    CDVPluginResult *result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsArray:command.arguments];
    [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
}

- (void) setMetaDataBool:(CDVInvokedUrlCommand *)command
{
    NSString *key = [command argumentAtIndex:0];
    BOOL toggle = [[command argumentAtIndex:1] boolValue];
    
    NSString *toggleStr = (toggle ? @"YES" : @"NO");

    [IronSource setMetaDataWithKey:key value:toggleStr];
    
    CDVPluginResult *result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsArray:command.arguments];
    [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
}

- (void) setSegment:(CDVInvokedUrlCommand *)command
{
    ISSegment *mIronSegment = [[ISSegment alloc]init];
    
    const NSDictionary *data = [command argumentAtIndex:0];
    const NSArray *keys = [data allKeys];

    for (int i = 0; i < [keys count]; i++) {

        NSString *key = [keys objectAtIndex:i];

        if ([key isEqualToString:@"segmentName"]){
            
            NSString *name = [data valueForKey:key];
            [mIronSegment setSegmentName:name];
            
        } else if ([key isEqualToString:@"age"]){
            
            const int age = [[data valueForKey:key] intValue];
            [mIronSegment setAge:age];
            
        } else if ([key isEqualToString:@"gender"]){
            
            const NSString *rGender = [[data valueForKey:key] stringValue];
            
            if ([rGender isEqualToString:@"male"]){
                
                [mIronSegment setGender:IRONSOURCE_USER_MALE ];
            } else if ([rGender isEqualToString:@"female"]){
                
                [mIronSegment setGender:IRONSOURCE_USER_FEMALE ];
            }
            
        } else if ([key isEqualToString:@"level"]){
            
            const int level = [[data valueForKey:key] intValue];
            [mIronSegment setLevel:level];
            
        } else if ([key isEqualToString:@"userCreationDate"]){
                   
            NSDate *date = [[NSDate alloc] initWithTimeIntervalSinceReferenceDate:[[data valueForKey:key] intValue]];
            [mIronSegment setUserCreationDate:date];
            
        } else if ([key isEqualToString:@"iapTotal"]){
            
            const double total = [[data valueForKey:key] doubleValue];
            [mIronSegment setIapTotal:total];
            
        } else if ([key isEqualToString:@"isPaying"]){
            
            const BOOL isPaying = [[data valueForKey:key] boolValue];
            [mIronSegment setPaying:isPaying];
            
        } else {
            
            NSString *value = [data valueForKey:key];
            [mIronSegment setCustomValue:value forKey:key];
        }
    }

    [IronSource setSegment:mIronSegment];
    
    CDVPluginResult *result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsArray:command.arguments];
    [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
}

# pragma mark - Advanced Settings :: Rewarded Video

- (void) setVideoServerParams:(CDVInvokedUrlCommand *)command
{
    NSDictionary *data = [command argumentAtIndex:0];
    NSArray *keys = [data allKeys];

    NSMutableDictionary *params = [[NSMutableDictionary alloc]init];

    for (int i = 0; i < [keys count]; i++) {

        NSString *key = [keys objectAtIndex:i];
        NSString *value = [data valueForKey:key];

        [params setObject:value forKey:key];
    }

    [IronSource setRewardedVideoServerParameters:params];

    CDVPluginResult *result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsArray:command.arguments];
    [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
}

- (void) clearVideoServerParams:(CDVInvokedUrlCommand *)command
{
    [IronSource clearRewardedVideoServerParameters];
    
    CDVPluginResult *result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsArray:command.arguments];
    [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
}

#pragma mark - Advanced Settings :: Offerwall

- (void) setOfferwallCustomParams:(CDVInvokedUrlCommand *)command
{
    NSDictionary *data = [command argumentAtIndex:0];
    NSArray *keys = [data allKeys];

    NSMutableDictionary *params = [[NSMutableDictionary alloc]init];

    for (int i = 0; i < [keys count]; i++) {

        NSString *key = [keys objectAtIndex:i];
        NSString *value = [data valueForKey:key];

        [params setObject:value forKey:key];
        
    }

    [ISConfigurations getConfigurations].offerwallCustomParameters = params;

    CDVPluginResult *result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsArray:command.arguments];
    [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
}

#pragma mark - Rewarded Video Advertisements

- (void) setShouldTrackNetworkState:(CDVInvokedUrlCommand *)command
{
    const BOOL track = [[command argumentAtIndex:0] boolValue];

    [IronSource shouldTrackReachability:track];
   
    CDVPluginResult *result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsArray:command.arguments];
    [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
}

- (void) isRewardVideoAvailable:(CDVInvokedUrlCommand *)command
{
    const BOOL isAvailable = [IronSource hasRewardedVideo];
    NSString *availabilityKey = @"isAvailable";

    NSMutableDictionary *data = [[NSMutableDictionary alloc]init];
    [data setObject:[NSNumber numberWithBool:isAvailable] forKey:availabilityKey];

    CDVPluginResult *result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:data];
    [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
}

- (void) showRewardedVideo:(CDVInvokedUrlCommand *)command
{
    NSString *placementName = [command argumentAtIndex:0];

    if ([placementName length] == 0)
    {
        [IronSource showRewardedVideoWithViewController:self.viewController];
    }
    else
    {
        [IronSource showRewardedVideoWithViewController:self.viewController placement:placementName ];
    }
    
    CDVPluginResult *result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsArray:command.arguments];
    [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
}

- (void) getVideoPlacementInfo:(CDVInvokedUrlCommand *)command
{
    NSString *placementName = [command argumentAtIndex:0];
    ISPlacementInfo *placementInfo = [IronSource rewardedVideoPlacementInfo:placementName];
    
    NSString *dictPlacementName = @"";
    NSString *dictRewardName = @"";
    NSNumber *dictRewardAmount = 0;

    if (placementInfo == NULL)
    {
        dictPlacementName = placementName;
    }
    else
    {
        dictPlacementName = placementInfo.placementName;
        dictRewardName = placementInfo.rewardName;
        dictRewardAmount = placementInfo.rewardAmount;
    }

    NSDictionary *data = @{
        @"placementName": dictPlacementName,
        @"rewardName": dictRewardName,
        @"rewardAmount": dictRewardAmount
    };
    
    CDVPluginResult *result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:data];
    [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
}

- (void) isVideoPlacementCapped:(CDVInvokedUrlCommand *)command
{
    NSString *placementName = [command argumentAtIndex:0];
    const BOOL isCapped = [IronSource isRewardedVideoCappedForPlacement:placementName];

    NSMutableDictionary *data = [[NSMutableDictionary alloc]init];
    [data setObject:[NSNumber numberWithBool:isCapped] forKey: @"isCapped"];
    [data setObject:placementName forKey: @"placementName"];

    CDVPluginResult *result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:data];
    [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
}

- (void) setDynamicUserID:(CDVInvokedUrlCommand *)command
{
    NSString *dynamicUserID = [command argumentAtIndex:0];
    [IronSource setDynamicUserId:dynamicUserID];
    
    CDVPluginResult *result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsArray:command.arguments];
    [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
}

#pragma mark - Interstitial Advertisements

- (void) createInterstitial:(CDVInvokedUrlCommand *)command
{
    [IronSource loadInterstitial];
    
    CDVPluginResult *result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsArray:command.arguments];
    [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
}

- (void) isInterstitialReady:(CDVInvokedUrlCommand *)command
{
    const BOOL isAvailable = [IronSource hasInterstitial];
    const NSString *availabilityKey = @"isReady";

    NSMutableDictionary *data = [[NSMutableDictionary alloc]init];
    [data setObject:[NSNumber numberWithBool:isAvailable] forKey: availabilityKey];

    CDVPluginResult *result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:data];
    [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
}

- (void) isInterstitialPlacementCapped:(CDVInvokedUrlCommand *)command
{
    NSString *placementName = [command argumentAtIndex:0];
    const BOOL isCapped = [IronSource isInterstitialCappedForPlacement:placementName];

    NSMutableDictionary *data = [[NSMutableDictionary alloc]init];
    [data setObject:[NSNumber numberWithBool: isCapped] forKey:@"isCapped"];
    [data setObject:placementName forKey:@"placementName"];
    
    CDVPluginResult *result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:data];
    [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
}

- (void) showInterstitial:(CDVInvokedUrlCommand *)command
{
    NSString *placementName = [command argumentAtIndex:0];

    if ([placementName length] == 0)
    {
        [IronSource showInterstitialWithViewController:self.viewController];
        
    }
    else
    {
        [IronSource showInterstitialWithViewController:self.viewController placement:placementName];
    }
    
    CDVPluginResult *result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsArray:command.arguments];
    [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
}

#pragma mark - Banner Advertisements

- (void)createBanner:(CDVInvokedUrlCommand *)command
{
    NSString *placementName = [command argumentAtIndex:0];

    BOOL top = [[command argumentAtIndex: 1] boolValue];

    NSNumber *size = [command argumentAtIndex:2]; // Enum: [Banner, Large, Rectangle, Smart, Custom]
    NSNumber *width = [command argumentAtIndex:3]; // Custom Width
    NSNumber *height = [command argumentAtIndex:4]; // Custom Height

    BOOL autoShow = [[command argumentAtIndex:5] boolValue]; // isAutoShow
    BOOL isAdaptiveBanner = [[command argumentAtIndex:6] boolValue]; // isAutoShow

    ISBannerSize *bannerSize;

    switch ([size intValue]) {

        case 0:
            bannerSize = ISBannerSize_BANNER;
            break;
        case 1:
            bannerSize = ISBannerSize_LARGE;
            break;
        case 2:
            bannerSize = ISBannerSize_RECTANGLE;
            break;
        case 3:
            bannerSize = ISBannerSize_SMART;
            break;
        default:
            bannerSize = [[ISBannerSize alloc] initWithWidth:[width intValue] andHeight:[height intValue]];
    }

    // Set adaptive banner
    bannerSize.adaptive = isAdaptiveBanner;

    bannerTop = top;
    bannerAutoShow = autoShow;
    
    for (UIView *subUIView in self.bannerController.view.subviews ) {
        [subUIView removeFromSuperview];
    }
    
    // We call destroy banner before loading a new banner
    [self _hideBanner];
    [self _destroyBanner];

    if ([placementName length] == 0) {
        
        [IronSource loadBannerWithViewController:self.bannerController size:bannerSize];
        
    } else {
        
        [IronSource loadBannerWithViewController:self.bannerController size:bannerSize placement:placementName];
    }
    
    CDVPluginResult *result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsArray:command.arguments];
    [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
}

- (void)showBanner:(CDVInvokedUrlCommand *)command
{
    [self _showBanner];
    
    CDVPluginResult *result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsArray:command.arguments];
    [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
}

- (void)hideBanner:(CDVInvokedUrlCommand *)command
{
    [self _hideBanner];

    CDVPluginResult *result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsArray:command.arguments];
    [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
}

- (void)destroyBanner:(CDVInvokedUrlCommand *)command
{
    [self _hideBanner];
    [self _destroyBanner];

    CDVPluginResult *result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsArray:command.arguments];
    [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
}

- (void)isBannerPlacementCapped:(CDVInvokedUrlCommand *)command
{
    NSString *placementName = [command argumentAtIndex:0];
    const BOOL isCapped = [IronSource isBannerCappedForPlacement:placementName];

    NSMutableDictionary *data = [[NSMutableDictionary alloc]init];
    [data setObject:[NSNumber numberWithBool:isCapped] forKey:@"isCapped"];
    [data setObject:placementName forKey:@"placementName"];

    CDVPluginResult *result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:data];
    [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
}

#pragma mark - Banner Tools

- (void)_showBanner
{
    if(self.bannerView && isBannerLoaded && !isBannerShowing)
     {
         [self.viewController.view addSubview:self.bannerView];
         [self.viewController.view bringSubviewToFront:self.bannerView];
         
         isBannerShowing = true;
     }
}

- (void)_hideBanner
{
    isBannerShowing = false;
    
    if(self.bannerView)
    {
        [self.bannerView removeFromSuperview];
    }
}

- (void)_destroyBanner
{
    isBannerLoaded = false;
    
    if (self.bannerView) {
        [IronSource destroyBanner:self.bannerView];
        self.bannerView = nil;
    }
}

- (void)_loadBanner:(ISBannerView *)bannerView
{
    CGFloat xOffset = .0f;
    CGFloat yOffset = .0f;
    
    CGFloat bannerHeight    = bannerView.frame.size.height;
    CGFloat bannerWidth     = bannerView.frame.size.width;

    UIScreen* mainScreen = [UIScreen mainScreen];

    CGFloat screenHeight = mainScreen.bounds.size.height;
    CGFloat screenWidth = mainScreen.bounds.size.width;
    
    CGFloat notchTop = .0f;
    CGFloat notchBottom = .0f;
    CGFloat notchLeft = .0f;
    CGFloat notchRight = .0f;
    
    // Allocated space for banner width. To prevent exceeding the notch.
    CGFloat screenWidthAlloc = screenWidth;

    if (@available(iOS 11.0, *))
    {
        notchTop = self.viewController.view.safeAreaInsets.top;
        notchBottom = self.viewController.view.safeAreaInsets.bottom;
        notchLeft = self.viewController.view.safeAreaInsets.left;
        notchRight = self.viewController.view.safeAreaInsets.right;
        
        // Setup the allocated space for banner width, for iOS 11.0+.
        screenWidthAlloc = (screenWidth - notchLeft - notchRight);
    }
    
    // If banner width exceeded the allocated space, with respect to the device's notch.
    if (bannerWidth > screenWidthAlloc)
    {
        bannerWidth = screenWidthAlloc;
    }
    
    xOffset = (screenWidthAlloc - bannerWidth) / 2;
    
    if (bannerTop)
    {
        yOffset = notchTop;
    }
    else
    {
        yOffset = screenHeight - bannerHeight - notchBottom;
    }

    CGRect bannerRect = CGRectMake(xOffset, yOffset, bannerWidth, bannerHeight);
    bannerView.frame = bannerRect;
}

#pragma mark - Offerwall Advertisements

- (void)showOfferwall:(CDVInvokedUrlCommand *)command
{
    NSString *placementName = [command argumentAtIndex:0];

    if ([placementName length] == 0)
    {
        [IronSource showOfferwallWithViewController:self.viewController];
    }
    else
    {
        [IronSource showOfferwallWithViewController:self.viewController placement:placementName];
    }
    
    CDVPluginResult *result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsArray:command.arguments];
    [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
}

-(void)getOfferwallCredits:(CDVInvokedUrlCommand *)command
{
    [IronSource offerwallCredits];
    
    CDVPluginResult *result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsArray:command.arguments];
    [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
}

-(void)setClientSideCallbacks:(CDVInvokedUrlCommand *)command
{
    NSNumber *receive = [NSNumber numberWithInt:[[command argumentAtIndex:0] intValue]];

    [ISSupersonicAdsConfiguration configurations].useClientSideCallbacks = receive;
    
    CDVPluginResult *result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsArray:command.arguments];
    [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
}

#pragma mark - Tools

- (void)getMode:(CDVInvokedUrlCommand *)command
{
    NSMutableDictionary *data = [[NSMutableDictionary alloc]init];
    [data setObject:[NSNumber numberWithBool:isBanner] forKey:@"isBanner"];
    [data setObject:[NSNumber numberWithBool:isInterstitial] forKey:@"isInterstitial"];
    [data setObject:[NSNumber numberWithBool:isRewardedVideo] forKey:@"isRewardedVideo"];
    [data setObject:[NSNumber numberWithBool:isOfferwall] forKey:@"isOfferwall"];
    
    CDVPluginResult *result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:data];
    [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
}

- (void)setBannerOverlap:(CDVInvokedUrlCommand *)command
{
    BOOL overlap = [[command argumentAtIndex:0] boolValue];
    bannerOverlap = overlap;
    
    CDVPluginResult *result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsArray:command.arguments];
    [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
}

#pragma mark - Utilities

- (void)fireEventTrigger:(NSString *)event
{
    NSString *js = [NSString stringWithFormat:@"cordova.fireWindowEvent('%@')", event];
    [self.commandDelegate evalJs:js];
}

- (void)fireEventTrigger:(NSString *)event withData:(NSDictionary *)data
{
    NSError *error = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:data options:kNilOptions error:&error];

    NSString *output = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    NSString *js = [NSString stringWithFormat:@"cordova.fireWindowEvent('%@', %@)", event, output];
    [self.commandDelegate evalJs:js];
}

- (void)listSubviewsOfView:(UIView *)view {

    // Get the subviews of the view
    NSArray *subviews = [view subviews];

    // Return if there are no subviews
    if ([subviews count] == 0) return; // COUNT CHECK LINE

    for (UIView *subview in subviews) {

        // Do what you want to do with the subview
        NSLog(@"%@", subview);

        // List the subviews of subview
        [self listSubviewsOfView:subview];
    }
}
 
#pragma mark - Initialization Delegate

- (void)initializationDidComplete {
    
    NSLog(@"%s", __PRETTY_FUNCTION__);
    
    isInitialized = true;

    [self fireEventTrigger:EVENT_INITIALIZATION];
}

#pragma mark - Rewarded Video Delegate

- (void)didClickRewardedVideo:(ISPlacementInfo *)placementInfo {
    
    NSLog(@"%s", __PRETTY_FUNCTION__);

    if (placementInfo == NULL)
    {
        NSDictionary *data = @{
            
            @"placementName": @"",
            @"rewardName": @"",
            @"rewardAmount": @0
        };
        
        [self fireEventTrigger:EVENT_REWARDED_VIDEO_CLICKED withData:data];
    }
    else
    {
        NSDictionary *data = @{
            
            @"placementName": placementInfo.placementName,
            @"rewardName": placementInfo.rewardName,
            @"rewardAmount": placementInfo.rewardAmount
        };
        
        [self fireEventTrigger:EVENT_REWARDED_VIDEO_CLICKED withData:data];
    }
}

- (void)didReceiveRewardForPlacement:(ISPlacementInfo *)placementInfo {
    
  NSLog(@"%s", __PRETTY_FUNCTION__);

  if (placementInfo == NULL)
  {
    NSDictionary *data = @{
        
        @"placementName": @"",
        @"rewardName": @"",
        @"rewardAmount": @0
    };

    [self fireEventTrigger:EVENT_REWARDED_VIDEO_REWARDED withData:data];
  }
  else
  {
    NSDictionary *data = @{
        
        @"placementName": placementInfo.placementName,
        @"rewardName": placementInfo.rewardName,
        @"rewardAmount": placementInfo.rewardAmount
    };

    [self fireEventTrigger:EVENT_REWARDED_VIDEO_REWARDED withData:data];
  }
}

- (void)rewardedVideoDidClose {
    
    NSLog(@"%s", __PRETTY_FUNCTION__);
    
    [self fireEventTrigger:EVENT_REWARDED_VIDEO_CLOSED];
}

- (void)rewardedVideoDidEnd {
  
    NSLog(@"%s", __PRETTY_FUNCTION__);
    
    [self fireEventTrigger:EVENT_REWARDED_VIDEO_ENDED];
}

- (void)rewardedVideoDidFailToShowWithError:(NSError *)error {
  
    NSLog(@"%s", __PRETTY_FUNCTION__);

    NSDictionary *data = @{
                           @"error" : @{
                                   @"code" : @(error.code),
                                   @"message" : error.description
                                   }
                           };
    
    [self fireEventTrigger:EVENT_REWARDED_VIDEO_FAILED withData:data];
}

- (void)rewardedVideoDidOpen {
  
    NSLog(@"%s", __PRETTY_FUNCTION__);
    
    [self fireEventTrigger:EVENT_REWARDED_VIDEO_OPENED];
}

- (void)rewardedVideoDidStart {
  
    NSLog(@"%s", __PRETTY_FUNCTION__);
    
    [self fireEventTrigger:EVENT_REWARDED_VIDEO_STARTED];
}

- (void)rewardedVideoHasChangedAvailability:(BOOL)isAvailable {
  
    NSLog(@"Rewarded Video is currently available: %@ .", (isAvailable == true) ? @"YES" : @"NO");
    NSLog(@"%s", __PRETTY_FUNCTION__);
    
    NSDictionary *data = @{
        
        @"isAvailable": @(isAvailable)
    };
    
    [self fireEventTrigger:EVENT_REWARDED_VIDEO_AVAILABILITY_CHANGED withData:data];
}

#pragma mark - Banner Delegate

- (void)bannerDidDismissScreen {
  
    NSLog(@"%s", __PRETTY_FUNCTION__);
    [self fireEventTrigger:EVENT_BANNER_SCREEN_DISMISSED];
}

- (void)bannerDidFailToLoadWithError:(NSError *)error {
    
    NSLog(@"%s", __PRETTY_FUNCTION__);
    
    NSDictionary *data = @{
        @"error": @{
                @"code": @(error.code),
                @"message": error.description
        }
    };
    
    for (UIView *subUIView in self.bannerController.view.subviews ) {
        [subUIView removeFromSuperview];
    }

    [self listSubviewsOfView:self.bannerController.view];
    [self fireEventTrigger:EVENT_BANNER_FAILED_TO_LOAD withData:data];
}

- (void)bannerDidLoad:(ISBannerView *)bannerView {
        
    // Destroy banner before loading a new one.
    [self _destroyBanner];
    self.bannerView = bannerView;

    [self _loadBanner:bannerView];

    isBannerLoaded = true;
    
    if (bannerAutoShow) { [self _showBanner]; }
    
    NSLog(@"%s", __PRETTY_FUNCTION__);
    [self fireEventTrigger:EVENT_BANNER_LOADED];
}

- (void)bannerWillLeaveApplication {
  
    NSLog(@"%s", __PRETTY_FUNCTION__);
    [self fireEventTrigger:EVENT_BANNER_LEFT_APPLICATION];
}

- (void)bannerWillPresentScreen {
  
    NSLog(@"%s", __PRETTY_FUNCTION__);
    [self fireEventTrigger:EVENT_BANNER_SCREEN_PRESENTED];
}

- (void)didClickBanner {
    
  NSLog(@"%s", __PRETTY_FUNCTION__);
  [self fireEventTrigger:EVENT_BANNER_CLICKED];
}

#pragma mark - Offerwall Delegate

- (void)didFailToReceiveOfferwallCreditsWithError:(NSError *)error {
    
  NSLog(@"%s", __PRETTY_FUNCTION__);

  NSDictionary *data = @{
                         @"error" : @{
                                 @"code" : @(error.code),
                                 @"message" : error.description
                                 }
                         };
  
  [self fireEventTrigger:EVENT_OFFERWALL_CREDITS_FAILED withData:data];
}

- (BOOL)didReceiveOfferwallCredits:(NSDictionary *)creditInfo {
  
    NSLog(@"%s", __PRETTY_FUNCTION__);
    [self fireEventTrigger:EVENT_OFFERWALL_CREDITED withData:creditInfo];
    
    // Claim reward. [Claim reward automatically]
    return true;
}

- (void)offerwallDidClose {
    
  NSLog(@"%s", __PRETTY_FUNCTION__);
  [self fireEventTrigger:EVENT_OFFERWALL_CLOSED];
}

- (void)offerwallDidFailToShowWithError:(NSError *)error {
    
    NSLog(@"%s", __PRETTY_FUNCTION__);

    NSDictionary *data = @{
                           @"error" : @{
                                   @"code" : @(error.code),
                                   @"message" : error.description
                                   }
                           };

    [self fireEventTrigger:EVENT_OFFERWALL_SHOW_FAILED withData:data];
}

- (void)offerwallDidShow {
    
  NSLog(@"%s", __PRETTY_FUNCTION__);
  [self fireEventTrigger:EVENT_OFFERWALL_OPENED];
}

- (void)offerwallHasChangedAvailability:(BOOL)isAvailable {
  
    NSLog(@"%s", __PRETTY_FUNCTION__);

    NSDictionary *data = @{
        
        @"isAvailable" : @(isAvailable)
   };

    [self fireEventTrigger:EVENT_OFFERWALL_AVAILABILITY_CHANGED withData:data];
}

#pragma mark - Interstitial Delegate

- (void)didClickInterstitial {
  
    NSLog(@"%s", __PRETTY_FUNCTION__);
    [self fireEventTrigger:EVENT_INTERSTITIAL_CLICKED];
}

- (void)interstitialDidClose {
  
    NSLog(@"%s", __PRETTY_FUNCTION__);
    [self fireEventTrigger:EVENT_INTERSTITIAL_CLOSED];
}

- (void)interstitialDidFailToLoadWithError:(NSError *)error {

     NSLog(@"%s", __PRETTY_FUNCTION__);

     NSDictionary *data = @{
         
        @"error" : @{
                @"code" : @(error.code),
                @"message" : error.description
                }
    };

     [self fireEventTrigger:EVENT_INTERSTITIAL_LOAD_FAILED withData:data];
}

- (void)interstitialDidFailToShowWithError:(NSError *)error {
    
    NSLog(@"%s", __PRETTY_FUNCTION__);

    NSDictionary *data = @{
        
       @"error" : @{
               @"code" : @(error.code),
               @"message" : error.description
               }
   };

    [self fireEventTrigger:EVENT_INTERSTITIAL_SHOW_FAILED withData:data];
}

- (void)interstitialDidLoad {
    
    NSLog(@"%s", __PRETTY_FUNCTION__);
    [self fireEventTrigger:EVENT_INTERSTITIAL_READY];
}

- (void)interstitialDidOpen {
  
    NSLog(@"%s", __PRETTY_FUNCTION__);
    [self fireEventTrigger:EVENT_INTERSTITIAL_OPENED];
}

- (void)interstitialDidShow {
  
    NSLog(@"%s", __PRETTY_FUNCTION__);
    [self fireEventTrigger:EVENT_INTERSTITIAL_SHOW_SUCCEEDED];
}

#pragma mark - Segments Delegate

- (void)didReceiveSegement:(NSString *)segment {
  
    NSLog(@"%s", __PRETTY_FUNCTION__);
    
    NSDictionary *data = @{
      
        @"segment": segment
    };
    
    [self fireEventTrigger:EVENT_SEGMENT_RECEIVED withData:data];
}

@end
