//
//  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 kSMAMoPubCustomEventInfoAdSpaceIdKey = @"adspaceId";
static NSString *const kSMAMoPubInterstitialAdapterVersion = @"1.0.1";

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

@implementation SMAMoPubSmaatoInterstitialAdapter

+ (NSString *)version
{
    return kSMAMoPubInterstitialAdapterVersion;
}

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

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

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

    // 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:SMAInterstitial.mediationNetworkName dspCreativeId:nil dspName:nil],
                 [self getAdNetworkId]);
    [SmaatoSDK loadInterstitialForAdSpaceId:self.adSpaceId delegate:self];
}

- (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] %@: %@", SMAInterstitial.mediationNetworkName, errorMessage);

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

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

    return NO;
}

- (void)showInterstitialFromRootViewController:(UIViewController *)rootViewController
{
    MPLogAdEvent([MPLogEvent adShowAttemptForAdapter:SMAInterstitial.mediationNetworkName], [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:SMAInterstitial.mediationNetworkName code:kSMAErrorCodeNoAdAvailable userInfo:userInfo];

        MPLogAdEvent([MPLogEvent adShowFailedForAdapter:SMAInterstitial.mediationNetworkName error:error], [self getAdNetworkId]);
    }
}

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

#pragma mark - SMAInterstitialDelegate

- (void)interstitialDidLoad:(SMAInterstitial *)interstitial
{
    MPLogAdEvent([MPLogEvent adLoadSuccessForAdapter:SMAInterstitial.mediationNetworkName], [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:SMAInterstitial.mediationNetworkName 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:SMAInterstitial.mediationNetworkName], [self getAdNetworkId]);

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

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

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

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

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

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

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

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

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

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

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

@end
