import UIKit
import AdViewSDK
import GoogleMobileAds
import AdMobAdViewAdapter

fileprivate let storedImpDisplayInterstitial = "POSIDzuqwln00ml38"
fileprivate let adMobAdUnitDisplayInterstitial = "ca-app-pub-7283949697136772/3280121025"

class AdMobDisplayInterstitialViewController: InterstitialBaseViewController, FullScreenContentDelegate {

    private var admobAdUnit: MediationInterstitialAdUnit!
    private var mediationDelegate: AdViewAdMobMediationInterstitialUtils!
    private var interstitial: GoogleMobileAds.InterstitialAd?

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

    func createAd() {
        let gadRequest = Request()

        mediationDelegate = AdViewAdMobMediationInterstitialUtils(gadRequest: gadRequest)
        admobAdUnit = MediationInterstitialAdUnit(
            configId: storedImpDisplayInterstitial,
            mediationDelegate: mediationDelegate
        )

        admobAdUnit.fetchDemand { [weak self] _ in
            guard let self else { return }
            InterstitialAd.load(with: adMobAdUnitDisplayInterstitial, request: gadRequest) { ad, error in
                if let error {
                    AdViewDemoLogger.shared.error("\(error.localizedDescription)")
                    return
                }
                guard let ad else { return }
                self.interstitial = ad
                self.interstitial?.fullScreenContentDelegate = self
                self.interstitial?.present(from: self)
            }
        }
    }

    func ad(_ ad: FullScreenPresentingAd, didFailToPresentFullScreenContentWithError error: Error) {
        AdViewDemoLogger.shared.error("\(error.localizedDescription)")
    }
}
