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

enum InterstitialAdEvent {
  onAdLoaded,
  onAdLoadFailed,
  onAdDisplayFailed,
  onAdDisplayed,
  onAdClicked,
  onAdHidden,
}

typedef void InterstitialAdListener(InterstitialAdEvent event, {Map<dynamic, dynamic> arguments});

class InterstitialAd {

  static const Map<String, InterstitialAdEvent> methodToInterstitialAdEvent = <
      String,
      InterstitialAdEvent>{
    'onInterstitialAdLoaded': InterstitialAdEvent.onAdLoaded,
    'onInterstitialAdLoadFailed': InterstitialAdEvent.onAdLoadFailed,
    'onInterstitialAdDisplayFailed': InterstitialAdEvent.onAdDisplayFailed,
    'onInterstitialAdDisplayed': InterstitialAdEvent.onAdDisplayed,
    'onInterstitialAdClicked': InterstitialAdEvent.onAdClicked,
    'onInterstitialAdHidden': InterstitialAdEvent.onAdHidden,
  };

  static final Map<int, InterstitialAd?> allInterstitialAds = <int, InterstitialAd?>{};

  InterstitialAd({
    required this.adUnitId,
    this.adAmazonSlotId,
    this.listener,
  }) {
    assert(adUnitId != null && adUnitId.isNotEmpty);
    allInterstitialAds[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;

  InterstitialAdListener? listener;

  Future<bool?> load() {
    print("Ads applovin library InterstitialAd load");
    return invokeBooleanMethod("loadInterstitialAd", <String, dynamic>{
      'id': id,
      'adUnitId': adUnitId,
      'adAmazonSlotId': adAmazonSlotId,
    });
  }

  Future<bool?> show({String? placement}) {
    return invokeBooleanMethod("showInterstitialAd", MapUtils.filterOutNulls(<String, dynamic>{
      'id': id,
      "placement": placement
    }));
  }

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

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

  Future<int> getAdState() async {
    return await invokeIntMethod("getInterstitialAdState", <String, dynamic>{'id': id}) ??
        AdStatus.FAILED;
  }
}
