//
//  UbMoPubRewardedViewController.swift
//  sdk-demo-ios
//
//  Created by Smaato Inc on 03/03/2019.
//  Copyright © 2019 Smaato Inc. All rights reserved.
//

import Foundation
import MoPub
import SmaatoSDKRewardedAds
import SmaatoSDKUnifiedBidding

class UbMoPubRewardedViewController: UIViewController {

    @IBOutlet private weak var showButton: UIButton!
    @IBOutlet private weak var adBlock: AdBlockView!
    @IBOutlet private weak var adUnitIDLabel: UILabel!
    @IBOutlet private weak var adapterVersionLabel: UILabel!
    @IBOutlet private weak var scrollView: UIScrollView!

    @IBOutlet private weak var rewardedAdDidLoadLabel: UILabel!
    @IBOutlet private weak var rewardedAdDidFailToLoadLabel: UILabel!
    @IBOutlet private weak var rewardedAdDidFailToPlayLabel: UILabel!
    @IBOutlet private weak var rewardedAdWillAppearLabel: UILabel!
    @IBOutlet private weak var rewardedAdDidAppearLabel: UILabel!
    @IBOutlet private weak var rewardedAdWillDisappearLabel: UILabel!
    @IBOutlet private weak var rewardedAdDidDisappearLabel: UILabel!
    @IBOutlet private weak var rewardedAdDidExpireLabel: UILabel!
    @IBOutlet private weak var rewardedAdShouldRewardLabel: UILabel!
    @IBOutlet private weak var rewardedAdDidReceiveTapLabel: UILabel!
    @IBOutlet private weak var rewardedAdWillLeaveApplicationLabel: UILabel!

    var mopubModel: MopubUBModel!

    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
    }

    @IBAction func loadRewardedTapped(_ sender: Any) {
        resetLabels()
        adBlock.tip = MediationRewardedAdsTip.LoadingTip.rawValue
        
        let adUnitId = mopubModel.adUnitId
        MPRewardedVideo.setDelegate(self, forAdUnitId: adUnitId)
        SmaatoSDK.prebidRewardedInterstitial(forAdSpaceId: mopubModel.smaatoAdspaceId) {(bid: SMAUbBid?, error: Error?) in
            var bidKeyword: String?
            var bidExtra: [AnyHashable:Any]?
            
            if let smaatoBid = bid {
                bidKeyword = smaatoBid.mopubPrebidKeyword
                bidExtra = smaatoBid.metaData
            } else {
                print("SmaatoSDK PreBid error: \(String(describing: error?.localizedDescription))")
            }
            
            MPRewardedVideo.loadAd(withAdUnitID: adUnitId,
                                   keywords: bidKeyword,
                                   userDataKeywords: nil,
                                   location: nil,
                                   customerId: nil,
                                   mediationSettings: [],
                                   localExtras: bidExtra)
        }
    }

    @IBAction func showRewardedVideoTapped(_ sender: UIButton) {
        showButton.isEnabled = false

        if MPRewardedVideo.hasAdAvailable(forAdUnitID: mopubModel.adUnitId) {
            let reward = MPRewardedVideo.availableRewards(forAdUnitID: mopubModel.adUnitId)?.first as? MPRewardedVideoReward
            MPRewardedVideo.presentAd(forAdUnitID: mopubModel.adUnitId, from: self, with: reward)
        }
    }

    //MARK: Private

    private func setupUI() {
        self.title = "MoPub Rewarded"
        adapterVersionLabel.text = "Adapter version \(SMAMoPubSmaatoRewardedVideoAdapter.version() ?? "")"
        adBlock.tip = MediationRewardedAdsTip.TryLoadTip.rawValue
        adUnitIDLabel.text = mopubModel.adUnitId
        if #available(iOS 11.0, *) {
            scrollView.contentInsetAdjustmentBehavior = .never
        } else {
            // Fallback on earlier versions
            automaticallyAdjustsScrollViewInsets = false
        }
    }

    private func resetLabels() {
        rewardedAdDidLoadLabel.alpha = 0.2
        rewardedAdDidFailToLoadLabel.alpha = 0.2
        rewardedAdDidFailToPlayLabel.alpha = 0.2
        rewardedAdWillAppearLabel.alpha = 0.2
        rewardedAdDidAppearLabel.alpha = 0.2
        rewardedAdWillDisappearLabel.alpha = 0.2
        rewardedAdDidDisappearLabel.alpha = 0.2
        rewardedAdDidExpireLabel.alpha = 0.2
        rewardedAdShouldRewardLabel.alpha = 0.2
        rewardedAdDidReceiveTapLabel.alpha = 0.2
        rewardedAdWillLeaveApplicationLabel.alpha = 0.2
    }
}

extension UbMoPubRewardedViewController: MPRewardedVideoDelegate {

    func rewardedVideoAdDidLoad(forAdUnitID adUnitID: String!) {
        NSLog("\(#function)")
        resetLabels()
        showButton.isEnabled = true
        adBlock.tip = MediationRewardedAdsTip.LoadedTip.rawValue
        rewardedAdDidLoadLabel.alpha = 1
    }

    func rewardedVideoAdWillAppear(forAdUnitID adUnitID: String!) {
        NSLog("\(#function)")
        rewardedAdWillAppearLabel.alpha = 1
    }

    func rewardedVideoAdDidAppear(forAdUnitID adUnitID: String!) {
        NSLog("\(#function)")
        rewardedAdDidAppearLabel.alpha = 1
    }

    func rewardedVideoAdWillDisappear(forAdUnitID adUnitID: String!) {
        NSLog("\(#function)")
        rewardedAdWillDisappearLabel.alpha = 1
    }

    func rewardedVideoAdDidDisappear(forAdUnitID adUnitID: String!) {
        NSLog("\(#function)")
        rewardedAdDidDisappearLabel.alpha = 1
    }

    func rewardedVideoAdDidExpire(forAdUnitID adUnitID: String!) {
        NSLog("\(#function)")
        rewardedAdDidExpireLabel.alpha = 1
        adBlock.tip = MediationRewardedAdsTip.ExpiredTip.rawValue
    }

    func rewardedVideoAdWillLeaveApplication(forAdUnitID adUnitID: String!) {
        NSLog("\(#function)")
        rewardedAdWillLeaveApplicationLabel.alpha = 1
    }

    func rewardedVideoAdDidFailToLoad(forAdUnitID adUnitID: String!, error: Error!) {
        NSLog("\(#function)")
        adBlock.tip = MediationRewardedAdsTip.ErrorTip.rawValue
        rewardedAdDidFailToLoadLabel.alpha = 1
    }

    func rewardedVideoAdDidFailToPlay(forAdUnitID adUnitID: String!, error: Error!) {
        NSLog("\(#function)")
        rewardedAdDidFailToPlayLabel.alpha = 1
        adBlock.tip = MediationRewardedAdsTip.FailedToPlayTip.rawValue
    }

    func rewardedVideoAdShouldReward(forAdUnitID adUnitID: String!, reward: MPRewardedVideoReward!) {
        print("\(#function)")
        rewardedAdShouldRewardLabel.alpha = 1
        NSLog("Reward: \(String(describing: reward.amount)) \(String(describing: reward.currencyType))")
    }

    func rewardedVideoAdDidReceiveTapEvent(forAdUnitID adUnitID: String!) {
        NSLog("\(#function)")
        rewardedAdDidReceiveTapLabel.alpha = 1
    }
}

