import UIKit
import AdViewSDK
import AppLovinMediationAdViewAdapter
import AppLovinSDK

fileprivate let storedMrecImpDisplayBanner = "POSIDcsts715vz17x"
fileprivate let maxAdUnitMrecBannerRendering = "a399e70b998ab175"

class MAXMrecBannerViewController: BannerBaseViewController, MAAdViewAdDelegate {

    private var maxAdUnit: MediationBannerAdUnit!
    private var maxMediationDelegate: AdViewMAXMediationBannerUtils!
    private var maxAdBannerView: MAAdView!

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

    func createAd() {
        maxAdBannerView = MAAdView(
            adUnitIdentifier: maxAdUnitMrecBannerRendering,
            adFormat: .mrec
        )

        maxAdBannerView.frame = CGRect(origin: .zero, size: adSize)
        maxAdBannerView.delegate = self
        maxAdBannerView.isHidden = false

        AdViewMAXBannerConfigIdBridge.shared.register(
            adUnitIdentifier: maxAdUnitMrecBannerRendering,
            configId: storedMrecImpDisplayBanner
        )

        bannerView.backgroundColor = .clear
        bannerView.addSubview(maxAdBannerView)

        maxMediationDelegate = AdViewMAXMediationBannerUtils(adView: maxAdBannerView)
        maxAdUnit = MediationBannerAdUnit(
            configID: storedMrecImpDisplayBanner,
            size: adSize,
            mediationDelegate: maxMediationDelegate
        )
        maxAdUnit.adFormat = .banner

        maxAdUnit.fetchDemand { [weak self] _ in
            self?.maxAdBannerView.loadAd()
        }
    }

    func didLoad(_ ad: MAAd) {}

    func didFail(toDisplay ad: MAAd, withError error: MAError) {
        AdViewDemoLogger.shared.error("\(error.message)")
        let nsError = NSError(
            domain: "MAX",
            code: error.code.rawValue,
            userInfo: [NSLocalizedDescriptionKey: error.message]
        )
        maxAdUnit.adObjectDidFailToLoadAd(adObject: maxAdBannerView, with: nsError)
    }

    func didFailToLoadAd(forAdUnitIdentifier adUnitIdentifier: String, withError error: MAError) {
        AdViewDemoLogger.shared.error("\(error.message)")
        let nsError = NSError(
            domain: "MAX",
            code: error.code.rawValue,
            userInfo: [NSLocalizedDescriptionKey: error.message]
        )
        maxAdUnit.adObjectDidFailToLoadAd(adObject: maxAdBannerView, with: nsError)
    }

    func didDisplay(_ ad: MAAd) {}

    func didHide(_ ad: MAAd) {}

    func didExpand(_ ad: MAAd) {}

    func didCollapse(_ ad: MAAd) {}

    func didClick(_ ad: MAAd) {}
}
