// Author: fengshengxiong
// Date: 2024/6/25
// Description: 插页广告

import 'dart:io' show Platform;

import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:flutter/foundation.dart';
import 'package:google_mobile_ads/google_mobile_ads.dart';
import 'package:tone_snap/utils/log_util.dart';

class InterstitialAdManager {
  InterstitialAdManager._();

  static final InterstitialAdManager _instance = InterstitialAdManager._();

  factory InterstitialAdManager() => _instance;

  /// 加载和显示广告之间允许的最长持续时间
  final Duration maxCacheDuration = const Duration(hours: 4);

  /// 跟踪加载时间，这样我们就不会显示过期的广告
  DateTime? _appOpenLoadTime;

  InterstitialAd? _interstitialAd;
  bool isShowingAd = false;

  /// 插页广告单元id
  final adUnitId = Platform.isAndroid
      ? (kReleaseMode ? '' : 'ca-app-pub-3940256099942544/1033173712')
      : (kReleaseMode ? 'ca-app-pub-5684307632319406/2760767691' : 'ca-app-pub-3940256099942544/4411468910');

  /// 加载广告
  void loadAd() async {
    final List<ConnectivityResult> connectivityResult = await (Connectivity().checkConnectivity());
    if (connectivityResult.contains(ConnectivityResult.none)) {
      return;
    }
    if (isAdAvailable) {
      return;
    }
    InterstitialAd.load(
      adUnitId: adUnitId,
      request: const AdRequest(),
      adLoadCallback: InterstitialAdLoadCallback(
        onAdLoaded: (ad) {
          LogUtil.d('插页广告加载完成');
          _interstitialAd = ad;
          _appOpenLoadTime = DateTime.now();
        },
        onAdFailedToLoad: (LoadAdError error) {
          LogUtil.d('插页广告加载失败: $error');
        },
      ),
    );
  }

  /// 是否可以播放广告
  bool get isAdAvailable {
    return _interstitialAd != null;
  }

  /// 显示广告（如果存在且尚未显示）
  /// 如果先前缓存的广告已过期，则只加载并缓存新广告
  void showAdIfAvailable({Function()? onTap}) {
    if (!isAdAvailable) {
      LogUtil.d('尝试在可用之前显示广告');
      loadAd();
      if(onTap != null) onTap();
      return;
    }
    if (isShowingAd) {
      LogUtil.d('尝试在已显示广告的情况下显示广告');
      if(onTap != null) onTap();
      return;
    }
    if (DateTime.now().subtract(maxCacheDuration).isAfter(_appOpenLoadTime!)) {
      LogUtil.d('超过了最大缓存持续时间。正在加载另一个广告');
      _interstitialAd!.dispose();
      _interstitialAd = null;
      loadAd();
      if(onTap != null) onTap();
      return;
    }
    // 设置 fullScreenContentCallback 并显示广告
    _interstitialAd!.fullScreenContentCallback = FullScreenContentCallback(
      // 暂停应用程序中的活动或记录广告展示的时间
      onAdShowedFullScreenContent: (ad) {
        isShowingAd = true;
        LogUtil.d('$ad onAdShowedFullScreenContent');
      },
      // 更适合用于跟踪广告展示的次数和效果，以及执行与广告展示相关的操作
      onAdImpression: (ad) {
        LogUtil.d('$ad onAdImpression');
      },
      onAdFailedToShowFullScreenContent: (ad, error) {
        LogUtil.d('$ad onAdFailedToShowFullScreenContent: $error');
        isShowingAd = false;
        ad.dispose();
        _interstitialAd = null;

        if(onTap != null) onTap();
      },
      onAdDismissedFullScreenContent: (ad) {
        LogUtil.d('$ad onAdDismissedFullScreenContent');
        isShowingAd = false;
        ad.dispose();
        _interstitialAd = null;
        loadAd();

        if(onTap != null) onTap();
      },
      onAdClicked: (ad) {
        LogUtil.d('$ad onAdClicked');
      },
    );
    _interstitialAd!.show();
  }
}