import UIKit
import AdViewSDK
import AppLovinMediationAdViewAdapter
import AppLovinSDK

fileprivate let storedImpVideoRewarded = "POSIDxdsaplpm4ar1"
fileprivate let maxAdUnitRewardedId = "b94740e7df6f86d5"

class MAXVideoRewardedViewController: InterstitialBaseViewController, MARewardedAdDelegate {

    private var maxRewardedAdUnit: MediationRewardedAdUnit!
    private var mediationDelegate: AdViewMAXMediationRewardedUtils!
    private var maxRewarded: MARewardedAd!

    override func loadView() {
        super.loadView()
        createAd()
    }

    func createAd() {
        maxRewarded = MARewardedAd.shared(withAdUnitIdentifier: maxAdUnitRewardedId)
        mediationDelegate = AdViewMAXMediationRewardedUtils(rewardedAd: maxRewarded)
        maxRewardedAdUnit = MediationRewardedAdUnit(
            configId: storedImpVideoRewarded,
            mediationDelegate: mediationDelegate
        )

        maxRewardedAdUnit.fetchDemand { [weak self] _ in
            guard let self else { return }
            self.maxRewarded.delegate = self
            self.maxRewarded.load()
        }
    }

    func didLoad(_ ad: MAAd) {
        if maxRewarded.isReady {
            maxRewarded.show()
        }
    }

    func didFail(toDisplay ad: MAAd, withError error: MAError) {
        AdViewDemoLogger.shared.error("\(error.message)")
    }

    func didFailToLoadAd(forAdUnitIdentifier adUnitIdentifier: String, withError error: MAError) {
        AdViewDemoLogger.shared.error("\(error.message)")
    }

    func didDisplay(_ ad: MAAd) {}

    func didHide(_ ad: MAAd) {}

    func didClick(_ ad: MAAd) {}

    func didRewardUser(for ad: MAAd, with reward: MAReward) {
        AdViewDemoLogger.shared.info("User did earn reward: label - \(reward.label), amount - \(reward.amount)")
    }
}
