import UIKit
import AdViewSDK
import GoogleMobileAds
import AdMobAdViewAdapter

fileprivate let storedImpDisplayBanner = "POSIDjw2dypnd7yv8"
fileprivate let adMobAdUnitDisplayBannerRendering = "ca-app-pub-7283949697136772/3397053982"

class AdMobDisplayBannerViewController: BannerBaseViewController, GoogleMobileAds.BannerViewDelegate {

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

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

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

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

    private func reattachBannerIfNeeded() {
        guard let banner = gadBanner else { return }
        banner.rootViewController = self
        guard banner.superview != bannerView else { return }
        bannerView.addSubview(banner)
    }

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

        let gadRequest = Request()
        
        AdViewAdMobUtils.setConfigIdOnRequest(storedImpDisplayBanner, request: gadRequest)

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


        bannerView.addSubview(gadBanner)

        mediationDelegate = AdViewAdMobMediationBannerUtils(gadRequest: gadRequest, bannerView: gadBanner)
        adviewAdMobMediationAdUnit = MediationBannerAdUnit(
            configID: storedImpDisplayBanner,
            size: adSize,
            mediationDelegate: mediationDelegate
        )
        
        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)
    }
}
