import UIKit
import AdViewSDK
import AppLovinMediationAdViewAdapter
import AppLovinSDK

fileprivate let storedImpDisplayBanner = "POSIDjw2dypnd7yv8"
fileprivate let maxAdUnitBannerRendering = "e9ed8811b9c85332"

class MAXDisplayBannerViewController: BannerBaseViewController, MAAdViewAdDelegate, MAAdRevenueDelegate {

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

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

    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        maxAdBannerView?.stopAutoRefresh()
        maxAdBannerView?.removeFromSuperview()
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        reattachBannerIfNeeded()
    }

    private func reattachBannerIfNeeded() {
        guard let banner = maxAdBannerView else { return }
        guard banner.superview != bannerView else { return }
        banner.frame = CGRect(origin: .zero, size: adSize)
        bannerView.addSubview(banner)
    }

    func createAd() {
        if maxAdUnit != nil {
            return
        }

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

        AdViewMAXBannerConfigIdBridge.shared.register(
            adUnitIdentifier: maxAdUnitBannerRendering,
            configId: storedImpDisplayBanner
        )

        bannerView.addSubview(maxAdBannerView)

        maxMediationDelegate = AdViewMAXMediationBannerUtils(adView: maxAdBannerView)
        maxAdUnit = MediationBannerAdUnit(
            configID: storedImpDisplayBanner,
            size: adSize,
            mediationDelegate: maxMediationDelegate
        )

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

    func didPayRevenue(for ad: MAAd) {
        AdViewDemoLogger.shared.info(
            "MAX Banner didPayRevenue · revenue=\(ad.revenue) · precision=\(ad.revenuePrecision) · network=\(ad.networkName) · adUnit=\(ad.adUnitIdentifier)"
        )
    }
}
