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

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

import 'package:applovin_max/applovin_max.dart';
import 'package:flutter/material.dart';
import 'package:now_wallpaper/common/utils/log_print.dart';

class ApplovinManage {
  ApplovinManage._();

  static final ApplovinManage _instance = ApplovinManage._();

  factory ApplovinManage() => _instance;

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

  /// 广告单元Id
  final String adUnitId1 = 'edc4bd530e79af75';
  final String adUnitId2 = '3f38d70ff5e85f92';
  final String adUnitId3 = '8a0fc2feeba310bc';

  /// 是否已初始化
  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({VoidCallback? onAdLoadedCallback}) {
    if (isInitialized) {
      AppLovinMAX.setInterstitialListener(InterstitialListener(
        onAdLoadedCallback: (ad) {
          LogPrint.d('插页广告加载成功:${ad.adUnitId}');
          if (ad.adUnitId == adUnitId1 && isSplashScreen) {
            isSplashScreen = false;
            onAdLoadedCallback!;
            showAdIfReady(adUnitId1);
            // AppLovinMAX.showInterstitial(adUnitId1);
            AppLovinMAX.loadInterstitial(adUnitId1);
          }
          _interstitialRetryAttempt = 0;
        },
        onAdLoadFailedCallback: (adUnitId, error) {
          LogPrint.d('插页广告加载失败adUnitId:$adUnitId,code:${error.code},message:${error.message}');
          if (adUnitId == adUnitId1 && isSplashScreen) {
            isSplashScreen = false;
          }
          // Applovin recommends that you retry with exponentially higher delays up to a maximum delay (in this case 64 seconds).
          _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();
        },
        onAdDisplayFailedCallback: (ad, error) {
          LogPrint.d('插页广告显示失败adUnitId:${ad.adUnitId},code:${error.code},message:${error.message}');
        },
        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;
  // }
}