import 'package:guru_app/ads/core/ads.dart';
import 'package:guru_app/ads/core/ads_config.dart';

// import 'package:guru_utils/ads/data/ads.dart';
import 'package:guru_utils/log/log.dart';
import 'package:guru_applovin_flutter/banner_ad.dart';
import 'package:guru_applovin_flutter/guru_applovin_flutter.dart';
import 'package:guru_utils/ads/ads.dart';

/// Created by Haoyi on 5/10/21

class ApplovinBannerAds extends BannerAds<BannerAdEvent> {
  late BannerAd bannerAd;
  @override
  final AdUnitId adUnitId;
  final AdSlotId? adAmazonSlotId;

  ApplovinBannerAds.create(this.adUnitId, this.adAmazonSlotId,
      {String? scene, AdsLifecycleObserver? observer}) {
    bannerAd = BannerAd(
        adUnitId: adUnitId.id, adAmazonSlotId: adAmazonSlotId?.id, listener: dispatchEvent);
    init();
    this.scene = scene ?? "";
    if (observer != null) {
      addObserver(observer);
    }
  }

  @override
  Map<BannerAdEvent, AdsEvent> get eventsMapping => {
        BannerAdEvent.onAdLoaded: AdsEvent.adLoaded,
        BannerAdEvent.onAdLoadFailed: AdsEvent.adLoadFailed,
        BannerAdEvent.onAdDisplayFailed: AdsEvent.adDisplayFailed,
        BannerAdEvent.onAdDisplayed: AdsEvent.adDisplayed,
        BannerAdEvent.onAdClicked: AdsEvent.adClick,
        BannerAdEvent.onAdHidden: AdsEvent.adHidden,
      };

  void hideOtherBanner() {
    // MoPubBannerAd.allBannerAds.forEach((key, value) {
    //   if (bannerAd.id != key) {
    //     value.hide();
    //   }
    // });
  }

  @override
  Future<bool> requestDispose() async {
    try {
      return await bannerAd.dispose() ?? false;
    } catch (error, stacktrace) {
      Log.d("dispose error:$error $stacktrace");
      return false;
    }
  }

  @override
  Future<bool> requestHide() async {
    try {
      return await bannerAd.hide() ?? false;
    } catch (error, stacktrace) {
      Log.d("requestHide error:$error $stacktrace");
      return false;
    }
  }

  @override
  Future<AdCause> requestLoad() async {
    try {
      Log.w("[$runtimeType] requestLoad", tag: "Ads");
      final result = await bannerAd.load(placement: scene) ?? false;
      if (result) {
        return AdCause.success;
      } else {
        return AdCause.requestFailed;
      }
    } catch (error, stacktrace) {
      Log.w("requestLoad error! $error  $stacktrace");
      return AdCause.internalError;
    }
  }

  @override
  Future<AdCause> requestShow({required String scene, bool ignoreCheck = false}) async {
    hideOtherBanner();
    try {
      final result = await bannerAd.show(anchorOffset: 3.0) ?? false;
      if (result) {
        return AdCause.success;
      } else {
        return AdCause.requestFailed;
      }
    } catch (error, stacktrace) {
      Log.i("Banner show error $error $stacktrace");
    }
    return AdCause.internalError;
  }

  Future<bool> checkLoaded() async {
    return true;
  }

  @override
  Future<int> getStatus() async {
    return AdStatus.LOADING;
  }
}
