//
//  SMAMoPubSmaatoBannerAdapter.m
//  SmaatoSDKAdapters
//
//  Created by Henning Buck on 29.10.18.
//  Copyright © 2018 Smaato. All rights reserved.
//

#import <SmaatoSDKBanner/SmaatoSDKBanner.h>
#import "SMAMoPubSmaatoBannerAdapter.h"

static NSString *const kSMAMoPubCustomEventInfoPublisherIdKey = @"publisherId";
static NSString *const kSMAMoPubCustomEventInfoAdSpaceIdKey = @"adspaceId";
static NSString *const kSMAMoPubBannerAdapterVersion = @"1.0.0";

@interface SMAMoPubSmaatoBannerAdapter () <SMABannerViewDelegate>
@property (nonatomic) SMABannerView *bannerView;
@end

@implementation SMAMoPubSmaatoBannerAdapter

+ (NSString *)version
{
    return kSMAMoPubBannerAdapterVersion;
}

- (void)requestAdWithSize:(CGSize)size customEventInfo:(NSDictionary *)info
{
    // Convert ad size format
    SMABannerAdSize convertedAdSize = [self SMABannerAdSizeFromRequestedSize:size];

    // Extract ad space information
    NSString *publisherId = info[kSMAMoPubCustomEventInfoPublisherIdKey];
    NSString *adSpaceId = info[kSMAMoPubCustomEventInfoAdSpaceIdKey];
    
    // Verify ad space information
    if (![self checkCredentialsWithAdSpaceId:adSpaceId publisherId:publisherId]) {
        return;
    }

    // Create and configure ad view object
    self.bannerView = [[SMABannerView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, size.width, size.height)];
    self.bannerView.delegate = self;
    self.bannerView.autoreloadInterval = kSMABannerAutoreloadIntervalDisabled;

    // Pass user location
    CLLocation *location = self.delegate.location;
    if (location) {
        SMALocation *userLocation = [[SMALocation alloc] initWithLatitude:location.coordinate.latitude
                                                                longitude:location.coordinate.longitude
                                                       horizontalAccuracy:location.horizontalAccuracy
                                                                timestamp:location.timestamp];
        SmaatoSDK.userLocation = userLocation;
    }

    /**
     Optional:
     You can also set specific user profile targeting parameters here.
     Please check the Smaato wiki for all available properties and further details.

     Examples:
     SmaatoSDK.userAge = 30;
     SmaatoSDK.userGender = kSMAGenderMale;
     */

    // Load ad
    SMABannerView.mediationNetworkName = NSStringFromClass([self class]);
    SMABannerView.mediationAdapterVersion = kSMAMoPubBannerAdapterVersion;
    SMABannerView.mediationNetworkSDKVersion = [[MoPub sharedInstance] version];
    [self.bannerView loadWithPublisherId:publisherId adSpaceId:adSpaceId adSize:convertedAdSize];
}

- (SMABannerAdSize)SMABannerAdSizeFromRequestedSize:(CGSize)requestedSize
{
    if (CGSizeEqualToSize(requestedSize, MOPUB_BANNER_SIZE)) {
        return kSMABannerAdSizeXXLarge_320x50;
    } else if (CGSizeEqualToSize(requestedSize, MOPUB_MEDIUM_RECT_SIZE)) {
        return kSMABannerAdSizeMediumRectangle_300x250;
    } else if (CGSizeEqualToSize(requestedSize, MOPUB_LEADERBOARD_SIZE)) {
        return kSMABannerAdSizeLeaderboard_728x90;
    } else if (CGSizeEqualToSize(requestedSize, MOPUB_WIDE_SKYSCRAPER_SIZE)) {
        return kSMABannerAdSizeSkyscraper_120x600;
    } else {
        return kSMABannerAdSizeAny;
    }
}

- (BOOL)checkCredentialsWithAdSpaceId:(NSString *)adSpaceId publisherId:(NSString *)publisherId
{
    if (publisherId && adSpaceId) {
        return YES;
    }
    
    NSString *errorMessage = @"PublisherId and/or AdSpaceId can not be extracted. Please check your configuration on MoPub dashboard.";
    NSLog(@"[SmaatoSDK] [Error] %@: %@", NSStringFromClass([self class]), errorMessage);
    
    if ([self.delegate respondsToSelector:@selector(bannerCustomEvent:didFailToLoadAdWithError:)]) {
        NSDictionary *userInfo = @{ NSLocalizedDescriptionKey : errorMessage };
        NSError *error = [NSError errorWithDomain:NSStringFromClass([self class]) code:kSMAErrorCodeInvalidRequest userInfo:userInfo];
        
        [self.delegate bannerCustomEvent:self didFailToLoadAdWithError:error];
    }
    
    return NO;
}

#pragma mark - SMABannerViewDelegate

- (UIViewController *)presentingViewControllerForBannerView:(SMABannerView *)bannerView
{
    return self.delegate.viewControllerForPresentingModalView;
}

- (void)bannerViewDidLoad:(SMABannerView *)bannerView
{
    if ([self.delegate respondsToSelector:@selector(bannerCustomEvent:didLoadAd:)]) {
        [self.delegate bannerCustomEvent:self didLoadAd:bannerView];
    }
}

- (void)bannerViewDidClick:(SMABannerView *)bannerView
{
    // No corresponding method from MoPub SDK available.
}

- (void)bannerView:(SMABannerView *)bannerView didFailWithError:(NSError *)error
{
    if ([self.delegate respondsToSelector:@selector(bannerCustomEvent:didFailToLoadAdWithError:)]) {
        [self.delegate bannerCustomEvent:self didFailToLoadAdWithError:error];
    }
}

- (void)bannerViewWillPresentModalContent:(SMABannerView *)bannerView
{
    if ([self.delegate respondsToSelector:@selector(bannerCustomEventWillBeginAction:)]) {
        [self.delegate bannerCustomEventWillBeginAction:self];
    }
}

- (void)bannerViewDidPresentModalContent:(SMABannerView *)bannerView
{
    // No corresponding method from MoPub SDK available.
}

- (void)bannerViewDidDismissModalContent:(SMABannerView *)bannerView
{
    if ([self.delegate respondsToSelector:@selector(bannerCustomEventDidFinishAction:)]) {
        [self.delegate bannerCustomEventDidFinishAction:self];
    }
}

- (void)bannerWillLeaveApplicationFromAd:(SMABannerView *)bannerView
{
    if ([self.delegate respondsToSelector:@selector(bannerCustomEventWillLeaveApplication:)]) {
        [self.delegate bannerCustomEventWillLeaveApplication:self];
    }
}

- (void)bannerViewDidTTLExpire:(SMABannerView *)bannerView
{
    // No corresponding method from MoPub SDK available.
}

@end
