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

enum RewardedVideoAdEvent {
  onAdLoaded,
  onAdLoadFailed,
  onAdDisplayFailed,
  onAdDisplayed,
  onAdClicked,
  onAdHidden,
  onRewardedVideoStarted,
  onRewardedVideoCompleted,
  onUserRewarded,
}

typedef void RewardedVideoAdListener(RewardedVideoAdEvent event, {Map<dynamic, dynamic> arguments});

class RewardedVideoAd {
  static const Map<String, RewardedVideoAdEvent> methodToRewardedVideoAdEvent = <String, RewardedVideoAdEvent>{
    'onRewardedVideoAdLoaded': RewardedVideoAdEvent.onAdLoaded,
    'onRewardedVideoAdLoadFailed': RewardedVideoAdEvent.onAdLoadFailed,
    'onRewardedVideoAdDisplayFailed': RewardedVideoAdEvent.onAdDisplayFailed,
    'onRewardedVideoAdDisplayed': RewardedVideoAdEvent.onAdDisplayed,
    'onRewardedVideoAdClicked': RewardedVideoAdEvent.onAdClicked,
    'onRewardedVideoAdHidden': RewardedVideoAdEvent.onAdHidden,
    'onRewardedVideoStarted': RewardedVideoAdEvent.onRewardedVideoStarted,
    'onRewardedVideoCompleted': RewardedVideoAdEvent.onRewardedVideoCompleted,
    'onRewardedVideoUserRewarded': RewardedVideoAdEvent.onUserRewarded,
  };

  static final Map<int, RewardedVideoAd> allRewardedVideoAds = <int, RewardedVideoAd>{};

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

  RewardedVideoAdListener? listener;

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

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

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

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

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