import UIKit
import AdViewSDK
import GoogleMobileAds
import AdMobAdViewAdapter

fileprivate let storedImpVideoRewarded = "POSIDxdsaplpm4ar1"
fileprivate let adMobAdUnitVideoRewardedId = "ca-app-pub-7283949697136772/4732803494"

class AdMobVideoRewardedViewController: InterstitialBaseViewController, FullScreenContentDelegate {

    private var admobRewardedAdUnit: MediationRewardedAdUnit!
    private var mediationDelegate: AdViewAdMobMediationRewardedUtils!
    private var gadRewardedAd: RewardedAd?

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

    func createAd() {
        let request = Request()

        mediationDelegate = AdViewAdMobMediationRewardedUtils(gadRequest: request)
        admobRewardedAdUnit = MediationRewardedAdUnit(
            configId: storedImpVideoRewarded,
            mediationDelegate: mediationDelegate
        )

        admobRewardedAdUnit.fetchDemand { [weak self] _ in
            guard let self else { return }
            RewardedAd.load(with: adMobAdUnitVideoRewardedId, request: request) { ad, error in
                if let error {
                    AdViewDemoLogger.shared.error("\(error.localizedDescription)")
                    return
                }
                guard let ad else { return }
                self.gadRewardedAd = ad
                self.gadRewardedAd?.fullScreenContentDelegate = self
                DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
                    self.gadRewardedAd?.present(from: self) {
                        AdViewDemoLogger.shared.info("User did earn reward.")
                    }
                }
            }
        }
    }

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