import UIKit
import AdViewSDK
import GoogleMobileAds
import AdMobAdViewAdapter

fileprivate let storedMrecImpDisplayBanner = "POSIDcsts715vz17x"
fileprivate let adMobAdUnitMrecBannerRendering = "ca-app-pub-7283949697136772/3397053982"

class AdMobMrecBannerViewController: BannerBaseViewController, GoogleMobileAds.BannerViewDelegate {

    private var adviewAdMobMediationAdUnit: MediationBannerAdUnit!
    private var mediationDelegate: AdViewAdMobMediationBannerUtils!
    private var gadBanner: GoogleMobileAds.BannerView!

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

    func createAd() {
        let gadRequest = Request()
        AdViewAdMobUtils.setConfigIdOnRequest(storedMrecImpDisplayBanner, request: gadRequest)

        gadBanner = GoogleMobileAds.BannerView(adSize: adSizeFor(cgSize: adSize))
        gadBanner.adUnitID = adMobAdUnitMrecBannerRendering
        gadBanner.delegate = self
        gadBanner.rootViewController = self

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

        mediationDelegate = AdViewAdMobMediationBannerUtils(gadRequest: gadRequest, bannerView: gadBanner)
        adviewAdMobMediationAdUnit = MediationBannerAdUnit(
            configID: storedMrecImpDisplayBanner,
            size: adSize,
            mediationDelegate: mediationDelegate
        )
        adviewAdMobMediationAdUnit.adFormat = .banner

        adviewAdMobMediationAdUnit.fetchDemand { [weak self] _ in
            self?.gadBanner.load(gadRequest)
        }
    }

    func bannerView(_ bannerView: GoogleMobileAds.BannerView, didFailToReceiveAdWithError error: Error) {
        AdViewDemoLogger.shared.error("\(error.localizedDescription)")
        adviewAdMobMediationAdUnit.adObjectDidFailToLoadAd(adObject: gadBanner, with: error)
    }
}
