// Author: fengshengxiong
// Date: 2024/5/20
// Description: 广告管理

import 'dart:async';
import 'dart:io';
import 'dart:math';

import 'package:applovin_max/applovin_max.dart';
import 'package:hello_wallpaper/common/utils/log_print.dart';
import 'package:hello_wallpaper/firebase/analytics_util.dart';

class ApplovinManage {
  ApplovinManage._();

  static final ApplovinManage _instance = ApplovinManage._();

  factory ApplovinManage() => _instance;

  /// sdkKey
  final String applovinKey = 'nEo4OHOhAZuAK9-IARuNaUfW-yDLBayq9FIGZs0L9XMNTByuDV6dsvMEIGnEAkQu-KR8D42QdKRlbniP910xnK';

  /// 广告单元Id
  final String adUnitId1 = Platform.isAndroid ? 'a2ced77c3755055b' : 'a2ced77c3755055b';
  final String adUnitId2 = Platform.isAndroid ? 'a3819ba97232d772' : 'a3819ba97232d772';
  final String adUnitId3 = Platform.isAndroid ? 'bb0bfc77dcfd1fc4' : 'bb0bfc77dcfd1fc4';

  /// 是否已初始化
  bool isInitialized = false;

  /// 是否是启动屏幕
  bool isSplashScreen = true;

  /// 重试计数
  final _maxExponentialRetryCount = 6;
  var _interstitialRetryAttempt = 0;

  /// 倒计时30秒，3个广告单元不重复展示
  // Timer? _timer;
  // int _timeCount = 30;

  /// 初始化
  Future<void> initApplovin() async {
    MaxConfiguration? configuration = await AppLovinMAX.initialize(applovinKey);
    if (configuration != null) {
      isInitialized = true;
    }
  }

  /// 初始化插页广告
  void initializeInterstitialAds({required Function() onGoHomeTap}) {
    if (isInitialized) {
      AppLovinMAX.setInterstitialListener(InterstitialListener(
        onAdLoadedCallback: (ad) async {
          LogPrint.d('插页广告加载成功:${ad.adUnitId}');
          if (ad.adUnitId == adUnitId1 && isSplashScreen) {
            await showAdIfReady(adUnitId1);
            AppLovinMAX.loadInterstitial(adUnitId1);
            isSplashScreen = false;
            onGoHomeTap();
          }
          _interstitialRetryAttempt = 0;
        },
        onAdLoadFailedCallback: (adUnitId, error) {
          LogPrint.d('插页广告加载失败adUnitId:$adUnitId,code:${error.code},message:${error.message}');
          if (adUnitId == adUnitId1 && isSplashScreen) {
            isSplashScreen = false;
            onGoHomeTap();
          }
          // Applovin建议您以指数级更高的延迟重试，最大延迟可达64秒
          _interstitialRetryAttempt = _interstitialRetryAttempt + 1;
          if (_interstitialRetryAttempt > _maxExponentialRetryCount) return;
          int retryDelay = pow(2, min(_maxExponentialRetryCount, _interstitialRetryAttempt)).toInt();

          Future.delayed(Duration(milliseconds: retryDelay * 1000), () {
            AppLovinMAX.loadInterstitial(adUnitId);
          });
        },
        onAdDisplayedCallback: (ad) {
          LogPrint.d('插页广告显示成功:${ad.adUnitId}');
          // _startTimer();
          // 打点
          AnalyticsUtil.logAdImpression(ad.adUnitId, ad.networkName, 1, 1, 0);
        },
        onAdDisplayFailedCallback: (ad, error) {
          LogPrint.d('插页广告显示失败adUnitId:${ad.adUnitId},code:${error.code},message:${error.message}');
          // 打点
          AnalyticsUtil.logAdImpression(ad.adUnitId, ad.networkName, 1, 0, 1);
        },
        onAdClickedCallback: (ad) {},
        onAdHiddenCallback: (ad) {
          LogPrint.d('插页广告隐藏:${ad.adUnitId}');
          AppLovinMAX.loadInterstitial(ad.adUnitId);
        },
      ));

      AppLovinMAX.loadInterstitial(adUnitId1);
      AppLovinMAX.loadInterstitial(adUnitId2);
      AppLovinMAX.loadInterstitial(adUnitId3);
    }
  }

  /// 显示插页广告，如果准备好
  Future<void> showAdIfReady(String adUnitId) async {
    if (!isInitialized) {
      return;
    }

    bool isReady = (await AppLovinMAX.isInterstitialReady(adUnitId))!;
    if (isReady) {
      // if (_timeCount == 30) {
      //   AppLovinMAX.showInterstitial(adUnitId);
      // }
      AppLovinMAX.showInterstitial(adUnitId);
    } else {
      AppLovinMAX.loadInterstitial(adUnitId);
    }
  }

  // /// 开始定时器
  // void _startTimer() {
  //   _timer = Timer.periodic(const Duration(seconds: 1), (Timer t) {
  //     if (_timeCount > 0) {
  //       _timeCount--;
  //       LogPrint.d('广告间隔倒计时$_timeCount秒');
  //     } else {
  //       _stopTimer();
  //       LogPrint.d('广告间隔计时停止');
  //     }
  //   });
  // }
  //
  // /// 停止定时器
  // void _stopTimer() {
  //   _timer?.cancel();
  //   _timer = null;
  //   _timeCount = 30;
  // }
}