import UIKit
import AdViewSDK
import GoogleMobileAds
import AdMobAdViewAdapter

fileprivate let storedImpVideoInterstitial = "POSIDxdsaplpm4ar1"
fileprivate let adMobAdUnitDisplayInterstitial = "ca-app-pub-7283949697136772/3280121025"

class AdMobVideoInterstitialViewController:
    InterstitialBaseViewController,
    FullScreenContentDelegate {
    
    
    private var admobAdUnit: MediationInterstitialAdUnit?
    private var mediationDelegate: AdViewAdMobMediationInterstitialUtils?
    
    // AdMob
    private var interstitial: GoogleMobileAds.InterstitialAd?
    
    override func loadView() {
        super.loadView()
        
        createAd()
    }
    
    func createAd() {
        // 1. Create a Request
        let gadRequest = Request()
        
        // 2. Create an AdViewAdMobMediationInterstitialUtils
        mediationDelegate = AdViewAdMobMediationInterstitialUtils(gadRequest: gadRequest)
        
        // 3. Create a MediationInterstitialAdUnit
        admobAdUnit = MediationInterstitialAdUnit(configId: storedImpVideoInterstitial, mediationDelegate: mediationDelegate!)
        
        // 4. Set ad format
        admobAdUnit?.adFormats = [.video]
        
        // 5. Make a bid request to AdView Server
        admobAdUnit?.fetchDemand(completion: { [weak self] result in
            AdViewDemoLogger.shared.info("AdViewdemand fetch for AdMob \(result.name())")
            
            // 6. Load the interstitial ad
            InterstitialAd.load(
                with: adMobAdUnitDisplayInterstitial,
                request: gadRequest
            ) { [weak self] ad, error in
                guard let self = self else { return }
                
                if let error = error {
                    AdViewDemoLogger.shared.error("\(error.localizedDescription)")
                    return
                }
                
                // 7. Present the interstitial ad
                self.interstitial = ad
                self.interstitial?.fullScreenContentDelegate = self
                self.interstitial?.present(from: self)
            }
        })
    }
    
    // MARK: - GADFullScreenContentDelegate
    
    func ad(
        _ ad: FullScreenPresentingAd,
        didFailToPresentFullScreenContentWithError error: Error
    ) {
        AdViewDemoLogger.shared.error("AdMob did fail to receive ad with error: \(error.localizedDescription)")
    }
}
