import UIKit
import AdViewSDK
import AppLovinMediationAdViewAdapter
import AppLovinSDK

fileprivate let storedImpDisplayRewarded = "POSIDxdsaplpm4ar1"
fileprivate let maxAdUnitRewardedId = "b94740e7df6f86d5"

class MAXDisplayRewardedViewController: InterstitialBaseViewController, MARewardedAdDelegate {
    
    // adview
    private var maxRewardedAdUnit: MediationRewardedAdUnit!
    private var mediationDelegate: AdViewMAXMediationRewardedUtils!
    
    // MAX
    private var maxRewarded: MARewardedAd!
    
    override func loadView() {
        super.loadView()
        
        createAd()
    }
    
    func createAd() {
        // 1. Create a MARewardedAd
        maxRewarded = MARewardedAd.shared(withAdUnitIdentifier: maxAdUnitRewardedId)
        
        // 2. Create a AdViewMAXMediationRewardedUtils
        mediationDelegate = AdViewMAXMediationRewardedUtils(rewardedAd: maxRewarded)
        
        // 3. Create a MediationRewardedAdUnit
        maxRewardedAdUnit = MediationRewardedAdUnit(
            configId: storedImpDisplayRewarded,
            mediationDelegate: mediationDelegate
        )
        
        // 4. Make a bid request to AdView Server
        maxRewardedAdUnit.fetchDemand { [weak self] result in
            // 5. Load the rewarded ad
            Log.info("After fetchDemand: result=\(result.name())")
            self?.maxRewarded.delegate = self
            self?.maxRewarded.load()
        }
    }
    
    // MARK: - MARewardedAdDelegate
    
    func didLoad(_ ad: MAAd) {
        if let maxRewarded = maxRewarded, maxRewarded.isReady {
            maxRewarded.show()
        }
    }
    
    func didFailToLoadAd(forAdUnitIdentifier adUnitIdentifier: String, withError error: MAError) {
        AdViewDemoLogger.shared.error("\(error.message)")
    }
    
    func didFail(toDisplay ad: MAAd, 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) {
        print("User did earn reward: label - \(reward.label), amount - \(reward.amount)")
    }
}
