import 'dart:math';
import 'package:betting/commom/utils/adHelper.dart';
import 'package:betting/commom/utils/service/global_controller.dart';
import 'package:get/get.dart';
import 'package:google_mobile_ads/google_mobile_ads.dart';


class NativeAdManager {

  NativeAd? nativeAd;
  RxBool isLoaded = false.obs;
  int retryAttempt = 0;

  NativeAdManager();

  /// Load an NativeAd.
  void loadAd() {
    nativeAd = NativeAd(
      adUnitId: AdHelper.nativeAdUnitId,
      factoryId: 'listTileNativeAdFactory',
      request: const AdRequest(),
      listener: NativeAdListener(
        // Called when an ad is successfully received.
        onAdLoaded: (Ad ad) {
          isLoaded.value = true;
          retryAttempt = 0;

        },
        // Called when an ad request failed.
        onAdFailedToLoad: (Ad ad, LoadAdError error) {
          // Dispose the ad here to free resources.
          ad.dispose();
          retryAttempt = retryAttempt + 1;
          int retryDelay = pow(2, min(6, retryAttempt)).toInt();
          print("retryDelay $retryDelay");
          Future.delayed(Duration(milliseconds: retryDelay * 1000), () {
            loadAd();
          });
        },
        // Called when an ad opens an overlay that covers the screen.
        onAdOpened: (Ad ad) => print('Ad opened.'),
        // Called when an ad removes an overlay that covers the screen.
        onAdClosed: (Ad ad) {

        },
        // Called when an impression occurs on the ad.
        onAdImpression: (Ad ad) => print('Ad impression.'),
        // Called when a click is recorded for a NativeAd.
        onAdClicked: (Ad ad) => print('Ad clicked.'),
      ),
    );
    nativeAd?.load();
  }

  /// Whether an ad is available to be shown.
  bool get isAdAvailable {
    return nativeAd != null && isLoaded.value;
  }
}
