//
//  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

        MPRewardedVideo.setDelegate(self, forAdUnitId: mopubModel.adUnitId)
        SmaatoSDK.prebidRewardedInterstitial(forAdSpaceId: mopubModel.smaatoAdspaceId) { [weak self] (bid: SMAUbBid?, error: Error?) in
            var bidKeyword: String? = nil
            let adUnitId = self?.mopubModel.adUnitId
            
            if let smaatoBid = bid {
                bidKeyword = smaatoBid.mopubPrebidKeyword
            } else {
                print("SmaatoSDK PreBid error: \(String(describing: error?.localizedDescription))")
            }
            
            MPRewardedVideo.loadAd(withAdUnitID: adUnitId,
                    keywords: bidKeyword,
                    userDataKeywords: nil,
                    location: nil,
                    mediationSettings: [])
        }

    }

    @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
    }
}

