/// Created by Haoyi on 5/11/21
part of '../ads.dart';

class BannerAdsReportEventsObserver extends AdsLifecycleObserver {
  void _apply(AdsBundle adsBundle, void Function(BannerAds ads) callback) {
    if (adsBundle.ads is BannerAds) {
      try {
        callback(adsBundle.ads as BannerAds);
      } catch (error, stacktrace) {
        Log.i('BannerAdsReportEventsHandler apply error:$error, $stacktrace');
      }
    }
  }

  @override
  void onRequestLoad(AdsBundle adsBundle) {
    _apply(adsBundle, (ads) {
      GuruAnalytics.instance.logEventEx("bads_load");
    });
  }

  @override
  void onAdLoaded(AdsBundle adsBundle) {
    _apply(adsBundle, (ads) {
      // AnalyticsUtils.logEventEx("bads_loaded",
      //     parameters: {"duration": ads.elapsedTimeInMillisSinceStartLoadAds});
    });
  }

  @override
  void onAdLoadFailed(AdsBundle adsBundle) {
    _apply(adsBundle, (ads) {
      String errorCode = adsBundle.arguments["errorName"] ?? "Unknown";
      // TODO
      // AnalyticsUtils.logEventEx("bads_failed", itemCategory: "load", parameters: {
      //   "duration": ads.elapsedTimeInMillisSinceStartLoadAds,
      //   "error_code": errorCode
      // });
    });
  }

  @override
  void onAdDisplayFailed(AdsBundle adsBundle) {
    _apply(adsBundle, (ads) {
      String errorCode = adsBundle.arguments["errorName"] ?? "Unknown";
      // TODO
      // AnalyticsUtils.logEventEx("bads_failed",
      //     itemCategory: "imp",
      //     parameters: {"duration": ads.elapsedTimeInMillisSinceLoadedAds, "error_code": errorCode});
    });
  }

  @override
  void onAdDisplayed(AdsBundle adsBundle) {
    _apply(adsBundle, (ads) {
      // AnalyticsUtils.logAdImpression("bads_imp", AdTypeName.AD_TYPE_BANNER,
      //     scene: ads.scene,
      //     adName: ads.scene,
      //     parameters: {"duration": "${ads.elapsedTimeInMillisSinceLoadedAds}"});
    });
  }

  @override
  void onAdClicked(AdsBundle adsBundle) {
    _apply(adsBundle, (ads) {
      GuruAnalytics.instance.logAdClick("bads_clk", AdTypeName.AD_TYPE_BANNER,
          scene: ads.scene, adName: ads.scene);
      AiBi.instance.adsClk(AdsType.banner, adScene: ads.scene);
    });
  }

  @override
  void onAdHidden(AdsBundle adsBundle) {
    _apply(adsBundle, (ads) {
      GuruAnalytics.instance.logEventEx("bads_close", itemCategory: ads.scene);
      AiBi.instance.adsHide(AdsType.banner, adScene: ads.scene);
    });
  }
}
