import UIKit
import AdViewSDK
import GoogleMobileAds
import AdMobAdViewAdapter

fileprivate let storedImpDisplayRewarded = "POSIDxdsaplpm4ar1"
fileprivate let adMobAdUnitRewardedId = "ca-app-pub-7283949697136772/4732803494"

class AdMobDisplayRewardedViewController: 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: storedImpDisplayRewarded,
            mediationDelegate: mediationDelegate
        )

        admobRewardedAdUnit.fetchDemand { [weak self] _ in
            guard let self else { return }
            RewardedAd.load(with: adMobAdUnitRewardedId, 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)")
    }
}
