import UIKit
import AdViewSDK
import AppLovinMediationAdViewAdapter
import AppLovinSDK

fileprivate let storedImpDisplayInterstitial = "POSIDzuqwln00ml38"
fileprivate let maxAdUnitDisplayInterstitial = "d50565fd22a74074"

class MAXDisplayInterstitialViewController: 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: maxAdUnitDisplayInterstitial)
        maxMediationDelegate = AdViewMAXMediationInterstitialUtils(interstitialAd: maxInterstitial)
        maxAdUnit = MediationInterstitialAdUnit(
            configId: storedImpDisplayInterstitial,
            mediationDelegate: maxMediationDelegate
        )

        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) {}
}
