import 'package:guru_app/ads/core/ads.dart';
import 'package:guru_app/ads/core/strategy/ad_unit.dart';
import 'package:guru_app/property/app_property.dart';
import 'package:guru_applovin_flutter/guru_applovin_flutter.dart';

import '../../../../guru_app.dart';

/// Created by Haoyi on 2023/6/28

mixin AdUnitCache<T> on SingleAds<T> {
}

class AdUnitCacheObserver extends AdsLifecycleObserver {
  final String adsName;

  AdUnitCacheObserver(this.adsName);

  @override
  String get name => "$adsName-AdUnitCache";

  void _apply(AdsBundle adsBundle, void Function(AdUnitCache) callback) {
    if (adsBundle.ads is AdUnitCache) {
      callback(adsBundle.ads as AdUnitCache);
    }
  }

  @override
  void onAdDisplayed(AdsBundle adsBundle) {
    _apply(adsBundle, (adsCache) {
      adsCache.loaded = false;
    });
  }

  @override
  void onAdLoaded(AdsBundle adsBundle) {
    Log.i("[$name] onAdLoaded! ", tag: PropertyTags.strategyAds);
    _apply(adsBundle, (adsCache) {
      adsCache.loaded = true;
    });
  }

  @override
  void onAdLoadFailed(AdsBundle adsBundle) {
    Log.i("[$name] onAdLoadFailed! ", tag: PropertyTags.strategyAds);
    _apply(adsBundle, (adsCache) async {
      adsCache.loaded = false;
    });
  }

  @override
  void onAdDisplayFailed(AdsBundle adsBundle) {
    Log.i("[$name] onAdDisplayFailed! ", tag: PropertyTags.strategyAds);
    _apply(adsBundle, (adsCache) {
      adsCache.loaded = false;
    });
  }

  @override
  void onAdHidden(AdsBundle adsBundle) {
    Log.i("[$name] onHidden! ", tag: PropertyTags.strategyAds);
    _apply(adsBundle, (adsCache) async {
      final state = await adsCache.getStatus();
      if (state != AdStatus.LOADED && state != AdStatus.LOADING) {
        adsCache.loaded = false;
      } else {
        Log.d("[$name] onHidden ignore preload! AdsState: $state", tag: PropertyTags.strategyAds);
      }
    });
  }
}