import UIKit
import AdViewSDK
import AppLovinMediationAdViewAdapter
import AppLovinSDK

fileprivate let storedImpVideoInterstitial = "POSIDxdsaplpm4ar1"
fileprivate let maxAdUnitVideoInterstitial = "d50565fd22a74074"

class MAXVideoInterstitialViewController: InterstitialBaseViewController, MAAdDelegate {

    private var maxAdUnit: MediationInterstitialAdUnit!
    private var maxMediationDelegate: AdViewMAXMediationInterstitialUtils!
    private var maxInterstitial: MAInterstitialAd!

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

    func createAd() {
        maxInterstitial = MAInterstitialAd(adUnitIdentifier: maxAdUnitVideoInterstitial)
        maxMediationDelegate = AdViewMAXMediationInterstitialUtils(interstitialAd: maxInterstitial)
        maxAdUnit = MediationInterstitialAdUnit(
            configId: storedImpVideoInterstitial,
            mediationDelegate: maxMediationDelegate
        )
        maxAdUnit.adFormats = [.video]

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

    func didLoad(_ ad: MAAd) {
        if maxInterstitial.isReady {
            maxInterstitial.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) {}
}
