import 'package:flutter/foundation.dart';
import 'package:flutter/widgets.dart';
import 'package:guru_utils/collection/collectionutils.dart';
import 'guru_applovin_flutter.dart';

enum AnchorType { bottom, top }

enum BannerAdEvent {
  onAdLoaded,
  onAdLoadFailed,
  onAdHidden,
  onAdDisplayFailed,
  onAdDisplayed,
  onAdClicked,
  onAdExpanded,
  onAdCollapsed,
}

typedef void BannerAdListener(BannerAdEvent event, {Map<dynamic, dynamic> arguments});

class BannerAd {
  static const Map<String, BannerAdEvent> methodToBannerAdEvent = <String, BannerAdEvent>{
    'onBannerAdLoaded': BannerAdEvent.onAdLoaded,
    'onBannerAdLoadFailed': BannerAdEvent.onAdLoadFailed,
    'onBannerAdDisplayFailed': BannerAdEvent.onAdDisplayFailed,
    'onBannerAdDisplayed': BannerAdEvent.onAdDisplayed,
    'onBannerAdClicked': BannerAdEvent.onAdClicked,
    'onBannerAdHidden': BannerAdEvent.onAdHidden,
    'onBannerAdExpanded': BannerAdEvent.onAdExpanded,
    'onBannerAdCollapsed': BannerAdEvent.onAdCollapsed,
  };

  static final Map<int, BannerAd?> allBannerAds = <int, BannerAd?>{};

  BannerAd({
    required this.adUnitId,
    this.adAmazonSlotId,
    this.listener,
  }) {
    assert(adUnitId != null && adUnitId.isNotEmpty);
    allBannerAds[id] = this;
  }

//  static final String testAdUnitId = Platform.isAndroid
//      ? 'ca-app-pub-3940256099942544/5224354917'
//      : 'ca-app-pub-3940256099942544/1712485313';

  final String adUnitId;
  final String? adAmazonSlotId;

  int get id => hashCode;

  BannerAdListener? listener;

  Future<bool?> load(
      {double anchorOffset = 0.0, double horizontalCenterOffset = 0.0, AnchorType anchorType = AnchorType
          .bottom, String? placement}) {
    return invokeBooleanMethod("loadBannerAd", MapUtils.filterOutNulls(<String, dynamic>{
      'id': id,
      'adUnitId': adUnitId,
      'adAmazonSlotId': adAmazonSlotId,
      'anchorOffset': anchorOffset.toString(),
      'horizontalCenterOffset': horizontalCenterOffset.toString(),
      'anchorType': describeEnum(anchorType),
      'placement': placement
    }));
  }

  Future<bool?> show(
      {double anchorOffset = 0.0, double horizontalCenterOffset = 0.0, AnchorType anchorType = AnchorType
          .bottom}) {
    return invokeBooleanMethod("showBannerAd", <String, dynamic>{
      'id': id,
      'anchorOffset': anchorOffset.toString(),
      'horizontalCenterOffset': horizontalCenterOffset.toString(),
      'anchorType': describeEnum(anchorType)
    });
  }

  Future<bool?> hide() {
    return invokeBooleanMethod("hideBannerAd", <String, dynamic>{
      'id': id,
    });
  }

  Future<bool?> dispose() {
    assert(allBannerAds[id] != null);
    allBannerAds.remove(id);
    return invokeBooleanMethod("disposeBannerAd", <String, dynamic>{'id': id});
  }

}
