//
//  SMAMoPubSmaatoInterstitialAdapter.m
//  SmaatoSDKAdapters
//
//  Created by Smaato Inc on 13.11.18.
//  Copyright © 2018 Smaato Inc. All rights reserved.￼
//  Licensed under the Smaato SDK License Agreement￼
//  https://www.smaato.com/sdk-license-agreement/
//

#import <SmaatoSDKInterstitial/SmaatoSDKInterstitial.h>
#import "SMAMoPubSmaatoInterstitialAdapter.h"
#if __has_include("MoPub.h")
#import "MPLogging.h"
#endif

static NSString *const kSMAMoPubInterstitialAdapterServerAdSpaceIdKey = @"adspaceId";
static NSString *const kSMAMoPubInterstitialAdapterLocalCreativeIdKey = @"smaato_ubid";
static NSString *const kSMAMoPubInterstitialAdapterVersion = @"1.0.3";

@interface SMAMoPubSmaatoInterstitialAdapter () <SMAInterstitialDelegate>
@property (nonatomic) SMAInterstitial *interstitial;
@property (nonatomic, copy) NSString *adSpaceId;
@end

@implementation SMAMoPubSmaatoInterstitialAdapter

+ (NSString *)version
{
    return kSMAMoPubInterstitialAdapterVersion;
}

- (void)requestInterstitialWithCustomEventInfo:(NSDictionary *)info adMarkup:(NSString *)adMarkup
{
    // Passing mediation information
    SMAInterstitial.mediationNetworkName = [self smaatoMediationNetworkName];
    SMAInterstitial.mediationAdapterVersion = kSMAMoPubInterstitialAdapterVersion;
    SMAInterstitial.mediationNetworkSDKVersion = [[MoPub sharedInstance] version];

    // Extract ad space information
    self.adSpaceId = [self fetchValueForKey:kSMAMoPubInterstitialAdapterServerAdSpaceIdKey fromEventInfo:info];

    // Verify ad space information
    if (![self checkCredentialsWithAdSpaceId:self.adSpaceId]) {
        return;
    }

    // Unified Bidding support (if available)
    SMAAdRequestParams *adRequestParams = [SMAAdRequestParams new];
    adRequestParams.ubUniqueId = [self fetchValueForKey:kSMAMoPubInterstitialAdapterLocalCreativeIdKey fromEventInfo:self.localExtras];

    // 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
    MPLogAdEvent([MPLogEvent adLoadAttemptForAdapter:[self smaatoMediationNetworkName] dspCreativeId:nil dspName:nil],
                 [self getAdNetworkId]);
    [SmaatoSDK loadInterstitialForAdSpaceId:self.adSpaceId delegate:self requestParams:adRequestParams];
}

- (NSString *)fetchValueForKey:(NSString *)definedKey fromEventInfo:(NSDictionary *)info
{
    __block NSString *value;
    [info enumerateKeysAndObjectsUsingBlock:^(NSString *_Nonnull key, id _Nonnull obj, BOOL *_Nonnull stop) {
        if ([definedKey caseInsensitiveCompare:key] == NSOrderedSame) {
            value = obj;
            *stop = YES;
        }
    }];
    return value;
}

- (BOOL)checkCredentialsWithAdSpaceId:(NSString *)adSpaceId
{
    if (adSpaceId) {
        return YES;
    }

    NSString *errorMessage = @"AdSpaceId can not be extracted. Please check your configuration on MoPub dashboard.";
    MPLogInfo(@"[SmaatoSDK] [Error] %@: %@", [self smaatoMediationNetworkName], errorMessage);

    if ([self.delegate respondsToSelector:@selector(interstitialCustomEvent:didFailToLoadAdWithError:)]) {
        NSDictionary *userInfo = @{ NSLocalizedDescriptionKey : errorMessage };
        NSError *error = [NSError errorWithDomain:[self smaatoMediationNetworkName] code:kSMAErrorCodeInvalidRequest userInfo:userInfo];

        [self.delegate interstitialCustomEvent:self didFailToLoadAdWithError:error];
    }

    return NO;
}

- (void)showInterstitialFromRootViewController:(UIViewController *)rootViewController
{
    MPLogAdEvent([MPLogEvent adShowAttemptForAdapter:[self smaatoMediationNetworkName]], [self getAdNetworkId]);

    if (self.interstitial.availableForPresentation) {
        [self.interstitial showFromViewController:rootViewController];
    } else {
        NSString *errorMessage = @"Interstitial Ad is not available for presentation";
        NSDictionary *userInfo = @{ NSLocalizedDescriptionKey : errorMessage };
        NSError *error = [NSError errorWithDomain:[self smaatoMediationNetworkName] code:kSMAErrorCodeNoAdAvailable userInfo:userInfo];

        MPLogAdEvent([MPLogEvent adShowFailedForAdapter:[self smaatoMediationNetworkName] error:error], [self getAdNetworkId]);
    }
}

- (NSString *)getAdNetworkId
{
    return self.adSpaceId;
}

- (NSString *)smaatoMediationNetworkName
{
    return NSStringFromClass([self class]);
}

#pragma mark - SMAInterstitialDelegate

- (void)interstitialDidLoad:(SMAInterstitial *)interstitial
{
    MPLogAdEvent([MPLogEvent adLoadSuccessForAdapter:[self smaatoMediationNetworkName]], [self getAdNetworkId]);

    self.interstitial = interstitial;
    if ([self.delegate respondsToSelector:@selector(interstitialCustomEvent:didLoadAd:)]) {
        [self.delegate interstitialCustomEvent:self didLoadAd:interstitial];
    }
}

- (void)interstitial:(SMAInterstitial *)interstitial didFailWithError:(NSError *)error
{
    MPLogAdEvent([MPLogEvent adLoadFailedForAdapter:[self smaatoMediationNetworkName] error:error], [self getAdNetworkId]);

    if ([self.delegate respondsToSelector:@selector(interstitialCustomEvent:didFailToLoadAdWithError:)]) {
        [self.delegate interstitialCustomEvent:self didFailToLoadAdWithError:error];
    }
}

- (void)interstitialDidTTLExpire:(SMAInterstitial *)interstitial
{
    if ([self.delegate respondsToSelector:@selector(interstitialCustomEventDidExpire:)]) {
        [self.delegate interstitialCustomEventDidExpire:self];
    }
}

- (void)interstitialWillAppear:(SMAInterstitial *)interstitial
{
    MPLogAdEvent([MPLogEvent adWillAppearForAdapter:[self smaatoMediationNetworkName]], [self getAdNetworkId]);

    if ([self.delegate respondsToSelector:@selector(interstitialCustomEventWillAppear:)]) {
        [self.delegate interstitialCustomEventWillAppear:self];
    }
}

- (void)interstitialDidAppear:(SMAInterstitial *)interstitial
{
    MPLogAdEvent([MPLogEvent adShowSuccessForAdapter:[self smaatoMediationNetworkName]], [self getAdNetworkId]);
    MPLogAdEvent([MPLogEvent adDidAppearForAdapter:[self smaatoMediationNetworkName]], [self getAdNetworkId]);

    if ([self.delegate respondsToSelector:@selector(interstitialCustomEventDidAppear:)]) {
        [self.delegate interstitialCustomEventDidAppear:self];
    }
}

- (void)interstitialWillDisappear:(SMAInterstitial *)interstitial
{
    MPLogAdEvent([MPLogEvent adWillDisappearForAdapter:[self smaatoMediationNetworkName]], [self getAdNetworkId]);

    if ([self.delegate respondsToSelector:@selector(interstitialCustomEventWillDisappear:)]) {
        [self.delegate interstitialCustomEventWillDisappear:self];
    }
}

- (void)interstitialDidDisappear:(SMAInterstitial *)interstitial
{
    MPLogAdEvent([MPLogEvent adDidDisappearForAdapter:[self smaatoMediationNetworkName]], [self getAdNetworkId]);

    if ([self.delegate respondsToSelector:@selector(interstitialCustomEventDidDisappear:)]) {
        [self.delegate interstitialCustomEventDidDisappear:self];
    }
}

- (void)interstitialDidClick:(SMAInterstitial *)interstitial
{
    MPLogAdEvent([MPLogEvent adTappedForAdapter:[self smaatoMediationNetworkName]], [self getAdNetworkId]);

    if ([self.delegate respondsToSelector:@selector(interstitialCustomEventDidReceiveTapEvent:)]) {
        [self.delegate interstitialCustomEventDidReceiveTapEvent:self];
    }
}

- (void)interstitialWillLeaveApplication:(SMAInterstitial *)interstitial
{
    MPLogAdEvent([MPLogEvent adWillLeaveApplicationForAdapter:[self smaatoMediationNetworkName]], [self getAdNetworkId]);

    if ([self.delegate respondsToSelector:@selector(interstitialCustomEventWillLeaveApplication:)]) {
        [self.delegate interstitialCustomEventWillLeaveApplication:self];
    }
}

@end
