//
//  SMAMoPubSmaatoRewardedVideoAdapter.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 <SmaatoSDKRewardedAds/SmaatoSDKRewardedAds.h>
#import "SMAMoPubSmaatoRewardedVideoAdapter.h"
#if __has_include("MoPub.h")
#import "MPLogging.h"
#endif

static NSString *const kSMAMoPubCustomEventInfoAdSpaceIdKey = @"adspaceId";
static NSString *const kSMAMoPubVideoRewardedVideoAdapterVersion = @"1.0.1";

@interface SMAMoPubSmaatoRewardedVideoAdapter () <SMARewardedInterstitialDelegate>
@property (nonatomic) SMARewardedInterstitial *rewardedAd;
@property (nonatomic, copy) NSString *adSpaceId;
@end

@implementation SMAMoPubSmaatoRewardedVideoAdapter

+ (NSString *)version
{
    return kSMAMoPubVideoRewardedVideoAdapterVersion;
}

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

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

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

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

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

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

        [self.delegate rewardedVideoDidFailToLoadAdForCustomEvent:self error:error];
    }

    return NO;
}

- (void)presentRewardedVideoFromViewController:(UIViewController *)viewController
{
    MPLogAdEvent([MPLogEvent adShowAttemptForAdapter:SMARewardedInterstitial.mediationNetworkName], [self getAdNetworkId]);

    if (self.rewardedAd.availableForPresentation) {
        [self.rewardedAd showFromViewController:viewController];
    } else {
        NSString *errorMessage = @"Rewarded Ad is not available for presentation";
        NSDictionary *userInfo = @{ NSLocalizedDescriptionKey : errorMessage };
        NSError *error =
            [NSError errorWithDomain:SMARewardedInterstitial.mediationNetworkName code:kSMAErrorCodeNoAdAvailable userInfo:userInfo];

        MPLogAdEvent([MPLogEvent adShowFailedForAdapter:SMARewardedInterstitial.mediationNetworkName error:error], [self getAdNetworkId]);
        if ([self.delegate respondsToSelector:@selector(rewardedVideoDidFailToPlayForCustomEvent:error:)]) {
            [self.delegate rewardedVideoDidFailToPlayForCustomEvent:self error:error];
        }
    }
}

- (BOOL)hasAdAvailable
{
    return self.rewardedAd.availableForPresentation;
}

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

#pragma mark - SMARewardedInterstitialDelegate

- (void)rewardedInterstitialDidFail:(SMARewardedInterstitial *)rewardedInterstitial withError:(NSError *)error
{
    MPLogAdEvent([MPLogEvent adLoadFailedForAdapter:SMARewardedInterstitial.mediationNetworkName error:error], [self getAdNetworkId]);

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

- (void)rewardedInterstitialDidLoad:(SMARewardedInterstitial *)rewardedInterstitial
{
    MPLogAdEvent([MPLogEvent adLoadSuccessForAdapter:SMARewardedInterstitial.mediationNetworkName], [self getAdNetworkId]);

    self.rewardedAd = rewardedInterstitial;
    if ([self.delegate respondsToSelector:@selector(rewardedVideoDidLoadAdForCustomEvent:)]) {
        [self.delegate rewardedVideoDidLoadAdForCustomEvent:self];
    }
}

- (void)rewardedInterstitialDidReward:(SMARewardedInterstitial *)rewardedInterstitial
{
    if ([self.delegate respondsToSelector:@selector(rewardedVideoShouldRewardUserForCustomEvent:reward:)]) {
        // Smaato doesn't retrieve exact reward (currency and amount) after video ad completion, due to this reason
        // publisher should supply with mandatory rewardedVideoAdShouldReward() function calling himself.
        // Publisher has to add new reward in Mopub Dashboard for given RewardedVideo adUnitId and this reward will be forwarded to
        // publusher app, after rewarded video completion
        [self.delegate rewardedVideoShouldRewardUserForCustomEvent:self reward:nil];
    }
}

- (void)rewardedInterstitialDidTTLExpire:(SMARewardedInterstitial *)rewardedInterstitial
{
    if ([self.delegate respondsToSelector:@selector(rewardedVideoDidExpireForCustomEvent:)]) {
        [self.delegate rewardedVideoDidExpireForCustomEvent:self];
    }
}

- (void)rewardedInterstitialWillAppear:(SMARewardedInterstitial *)rewardedInterstitial
{
    MPLogAdEvent([MPLogEvent adWillAppearForAdapter:SMARewardedInterstitial.mediationNetworkName], [self getAdNetworkId]);

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

- (void)rewardedInterstitialDidAppear:(SMARewardedInterstitial *)rewardedInterstitial
{
    MPLogAdEvent([MPLogEvent adDidAppearForAdapter:SMARewardedInterstitial.mediationNetworkName], [self getAdNetworkId]);

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

- (void)rewardedInterstitialWillDisappear:(SMARewardedInterstitial *)rewardedInterstitial
{
    MPLogAdEvent([MPLogEvent adWillDisappearForAdapter:SMARewardedInterstitial.mediationNetworkName], [self getAdNetworkId]);

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

- (void)rewardedInterstitialDidDisappear:(SMARewardedInterstitial *)rewardedInterstitial
{
    MPLogAdEvent([MPLogEvent adDidDisappearForAdapter:SMARewardedInterstitial.mediationNetworkName], [self getAdNetworkId]);

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

- (void)rewardedInterstitialDidStart:(SMARewardedInterstitial *)rewardedInterstitial
{
    MPLogAdEvent([MPLogEvent adShowSuccessForAdapter:SMARewardedInterstitial.mediationNetworkName], [self getAdNetworkId]);
    // No corresponding delegate method from MoPub SDK available.
}

- (void)rewardedInterstitialDidClick:(SMARewardedInterstitial *)rewardedInterstitial
{
    MPLogAdEvent([MPLogEvent adTappedForAdapter:SMARewardedInterstitial.mediationNetworkName], [self getAdNetworkId]);

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

- (void)rewardedInterstitialWillLeaveApplication:(SMARewardedInterstitial *)rewardedInterstitial
{
    MPLogAdEvent([MPLogEvent adWillLeaveApplicationForAdapter:SMARewardedInterstitial.mediationNetworkName], [self getAdNetworkId]);

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

@end
