package flutter.guru.guru_applovin_flutter

import android.app.Activity
import android.content.Context
import android.util.Log
import android.view.Gravity
import androidx.annotation.NonNull
import com.amazon.device.ads.AdRegistration
import com.amazon.device.ads.DTBAdNetwork
import com.amazon.device.ads.DTBAdNetworkInfo
import com.amazon.device.ads.MRAIDPolicy
import com.applovin.sdk.AppLovinPrivacySettings
import com.applovin.sdk.AppLovinSdk
import com.applovin.sdk.AppLovinSdkConfiguration
import com.applovin.sdk.AppLovinSdkUtils
import com.google.android.gms.ads.MobileAds
import com.google.android.gms.ads.RequestConfiguration
import com.pubmatic.sdk.common.OpenWrapSDK
import com.pubmatic.sdk.common.models.POBApplicationInfo
import flutter.guru.guru_applovin_flutter.log.Logger
import guru.core.consent.gdpr.ConsentManager
import guru.core.consent.gdpr.ConsentRequest
import guru.core.consent.gdpr.ConsentStatus
import guru.core.consent.gdpr.GdprHelper
import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.embedding.engine.plugins.activity.ActivityAware
import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.common.MethodChannel.MethodCallHandler
import java.net.URL
import java.util.*
import java.util.concurrent.atomic.AtomicBoolean

/** GuruApplovinFlutterPlugin */
class GuruApplovinFlutterPlugin : FlutterPlugin, MethodCallHandler, ActivityAware {
    /// The MethodChannel that will the communication between Flutter and native Android
    ///
    /// This local reference serves to register the plugin with the Flutter Engine and unregister it
    /// when the Flutter Engine is detached from the Activity
    private lateinit var channel: MethodChannel
    private var applicationContext: Context? = null
    private var activity: Activity? = null
    private val initialized = AtomicBoolean(false)

    private val consentManager: ConsentManager by lazy {
        ConsentManager(activity!!)
    }

    override fun onAttachedToEngine(@NonNull flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) {
        Logger.d("Ads", "GuruApplovinFlutterPlugin onAttachedToEngine")
        channel = MethodChannel(flutterPluginBinding.binaryMessenger, "guru_applovin_flutter")
        channel.setMethodCallHandler(this)
    }

    override fun onMethodCall(@NonNull call: MethodCall, @NonNull result: MethodChannel.Result) {
        if (activity == null) {
            Logger.w("Ads", "GuruApplovinFlutterPlugin onMethodCall activity is null")
            result.error(
                "no_activity",
                "firebase_admob plugin requires a foreground activity",
                null
            )
            return
        }
        val id = if (call.arguments is Map<*, *>) {
            call.argument<Int>("id")
        } else {
            null
        }
        Logger.d("Ads", "GuruApplovinFlutterPlugin onMethodCall id: $id method:${call.method}")
        when (call.method) {
            "initialize" -> callInitialize(call, result)
            "gatherConsentAndInitialize" -> callGatherConsentAndInitialize(call, result)
            "requestGdpr" -> callRequestGdpr(call, result)
            "resetGdpr" -> callResetGdpr(call, result)
            "showPrivacyOptionsForm" -> callShowPrivacyOptionsForm(call, result)
            "loadRewardedVideoAd" -> callLoadRewardedVideoAd(id, call, result)
            "showRewardedVideoAd" -> callShowRewardedVideoAd(id, call, result)
            "loadInterstitialAd" -> callLoadInterstitialAd(id, call, result)
            "showInterstitialAd" -> callShowInterstitialAd(id, call, result)
            "isInterstitialAdLoaded" -> callInterstitialAdLoaded(id, result)
            "loadBannerAd" -> callLoadBannerAd(id, call, result)
            "showBannerAd" -> callShowBannerAd(id, call, result)
            "hideBannerAd" -> callHideBannerAd(id, result)
            "disposeBannerAd" -> callDisposeBannerAd(id, result)
            "disposeRewardedAd" -> callDisposeRewardedVideoAd(id, result)
            "getRewardedAdState" -> callGetRewardedAdsState(id, result)
            "disposeInterstitialAd" -> callDisposeInterstitialAd(id, result)
            "getInterstitialAdState" -> callGetInterstitialAdsState(id, result)
            "afterAcceptPrivacy" -> callAfterAcceptPrivacy(call, result)
            "checkConsentDialogStatus" -> callCheckConsentDialogStatus(result)
            "hasUserConsent" -> callHasUserConsent(result)
            "openDebugger" -> callOpenDebugger(result)
            "isTablet" -> callIsTablet(result)
            "setDebugMode" -> callSetDebugMode(call, result)
            "setKeywords" -> callSetKeywords(call, result)
            "clearTargetingData" -> callClearTargetingData(call, result)
            "getBannerAdSize" -> callGetBannerAdSize(call, result)
            "updateOrientation" -> callUpdateOrientation(call, result)
            else -> result.notImplemented()
        }
    }

    override fun onDetachedFromEngine(@NonNull binding: FlutterPlugin.FlutterPluginBinding) {
        channel.setMethodCallHandler(null)
    }

    override fun onAttachedToActivity(binding: ActivityPluginBinding) {
        Logger.d("Ads", "GuruApplovinFlutterPlugin onAttachedToActivity");
        attachActivity(binding.activity)
    }

    override fun onDetachedFromActivityForConfigChanges() {
    }

    override fun onReattachedToActivityForConfigChanges(binding: ActivityPluginBinding) {
    }

    override fun onDetachedFromActivity() {
        Logger.d("Ads", "GuruApplovinFlutterPlugin onDetachedFromActivity");
        detachActivity()
    }

    private fun attachActivity(activity: Activity?) {
        activity?.apply {
            AdHelp.attach(this)
            this@GuruApplovinFlutterPlugin.activity = this
            this@GuruApplovinFlutterPlugin.applicationContext = applicationContext
            Logger.initialize(this)
        }
    }

    private fun detachActivity() {
        BannerAd.disposeAll(activity)
        this.activity = null
        AdHelp.detach()
    }

    private fun callInitialize(methodCall: MethodCall, result: MethodChannel.Result) {
        if (!initialized.compareAndSet(false, true)) {
            Logger.d("Ads", "call already initialized! ignore!")
            return
        }
        val debugLog = methodCall.argument<Boolean>("debug_mode") ?: false
        val userId = methodCall.argument<String>("user_id") ?: ""

        //init amazon
        val amazonAppId = methodCall.argument<String?>("amazon_appId")
        if (!amazonAppId.isNullOrBlank() && activity != null) {
            AdRegistration.getInstance(amazonAppId, activity!!)
            AdRegistration.setAdNetworkInfo(DTBAdNetworkInfo(DTBAdNetwork.MAX))
            AdRegistration.setMRAIDSupportedVersions(arrayOf("1.0", "2.0", "3.0"))
            AdRegistration.setMRAIDPolicy(MRAIDPolicy.CUSTOM)
            AdRegistration.useGeoLocation(true)
            AdRegistration.enableLogging(debugLog)
//            AdRegistration.enableTesting(true)
        }

        val pubmaticStoreUrl = methodCall.argument<String?>("pubmatic_store_url")
        if (!pubmaticStoreUrl.isNullOrBlank() && activity != null) {
            val appInfo = POBApplicationInfo()
            try {
                appInfo.storeURL = URL(pubmaticStoreUrl)
            } catch (error: Throwable) {
            }
            OpenWrapSDK.setApplicationInfo(appInfo)
        }

        AppLovinSdk.getInstance(activity).mediationProvider = "max"
        AppLovinSdk.getInstance(activity).settings.isMuted = true
        if (userId.isNotEmpty()) {
            AppLovinSdk.getInstance(activity).setUserIdentifier(userId)
            Logger.d("Ads", "set userId$userId success");
        } else {
            Logger.d("Ads", "userId is null");
        }
        AppLovinSdk.getInstance(activity).settings.setVerboseLogging(debugLog)
        var isInvoked = false
        AppLovinSdk.getInstance(activity).initializeSdk {
            // AppLovin SDK is initialized, start loading ads
            if (!isInvoked) {
                result.success(true)
            }
            Logger.d("Ads", "AppLovinSdk initializeSdk success")
            isInvoked = true
        }
        if (activity != null) {
            MobileAds.initialize(activity!!) {
                MobileAds.setAppMuted(true)
                MobileAds.setAppVolume(0.0F)
            }
        }
    }

    private fun callRequestGdpr(methodCall: MethodCall, result: MethodChannel.Result) {
        Logger.d("GuruAds", "callRequestGdpr ${methodCall.argument<Int>("debug_geography")}")

        val debugGeography = methodCall.argument<Int>("debug_geography")
        val testDeviceId = methodCall.argument<String>("test_device_id")
        val deviceIds: Set<String> = if (testDeviceId != null) setOf(testDeviceId) else emptySet()
        Logger.d("GuruAds", "requestGdpr debugGeography:${debugGeography}, deviceIds:${deviceIds}")
        val request: ConsentRequest = ConsentRequest.Builder(activity!!)
            .debugGeography(debugGeography)
            .addDeviceIds(deviceIds)
            .withListener(object : ConsentRequest.Listener {
                override fun onConsentResult(status: Int) {
                    Logger.d("GuruAds", "onConsentResult:$status")
                    result.success(status)
                }

                override fun onConsentImpression() {
                    Logger.d("GuruAds", "onConsentImpression")

                }

                override fun onConsentLoadFailure() {
                    Logger.d("GuruAds", "onConsentLoadFailure")
                    result.success(ConsentStatus.NOT_AVAILABLE)
                }
            }).build()
        GdprHelper.request(request)
    }

    private fun callGatherConsentAndInitialize(
        methodCall: MethodCall,
        result: MethodChannel.Result
    ) {
        Logger.d(
            "GuruAds",
            "callGatherConsentAndInitialize ${methodCall.argument<Int>("debug_geography")}"
        )

        val debugGeography = methodCall.argument<Int>("debug_geography")
        val testDeviceId = methodCall.argument<String>("test_device_id")
        val deviceIds: Set<String> = if (testDeviceId != null) setOf(testDeviceId) else emptySet()
        Logger.d(
            "GuruAds",
            "callGatherConsentAndInitialize debugGeography:${debugGeography}, deviceIds:${deviceIds}"
        )
        val request: ConsentRequest = ConsentRequest.Builder(activity!!)
            .debugGeography(debugGeography)
            .addDeviceIds(deviceIds)
            .withConsentGatheringCompleteListener { error ->
                error?.let {
                    // Consent not obtained in current session.
                    Logger.d("GuruAds", "gather consent error! ${it.errorCode}: ${it.message}")
                }
                if (consentManager.canRequestAds) {
                    callInitialize(methodCall, result)
                }
            }.build()
        consentManager.gather(request)

        if (consentManager.canRequestAds) {
            callInitialize(methodCall, result)
        }
    }

    private fun callShowPrivacyOptionsForm(methodCall: MethodCall, result: MethodChannel.Result) {
        consentManager.showPrivacyOptionsForm(activity!!) { formError ->
            result.success(ConsentErrorCode.toConsentErrorCode(formError))
        }
    }

    private fun callResetGdpr(methodCall: MethodCall, result: MethodChannel.Result) {
        GdprHelper.reset(activity!!)
        result.success(true)
    }

    private fun callLoadRewardedVideoAd(
        id: Int?,
        methodCall: MethodCall,
        result: MethodChannel.Result
    ) {
        Logger.d("Ads", "RewardedVideo applovin native callLoadRewardedVideoAd")
        if (id == null) {
            Logger.w("Ads", "RewardedVideo applovin native callLoadRewardedVideoAd lose hash id")
            result.error("no_hash_id", "load rewardedVideoAd lose hash id", null)
        }

        var rewardedVideoAd = RewardedVideoAd.createRewardedVideo(id!!, channel!!)
        if (rewardedVideoAd.status == AdStatus.LOADED) {
            Logger.w("Ads", "RewardedVideo applovin native callLoadRewardedVideoAd ad is loaded")
            result.success(true) // The ad was already loaded or loading.
            return;
        }

        var adUnitId = methodCall.argument<String>("adUnitId")
        if (adUnitId.isNullOrEmpty()) {
            Logger.w(
                "Ads",
                "RewardedVideo applovin native callLoadRewardedVideoAd adUnitId is null or empty"
            )
            result.error(
                "no_adunit_id",
                "a null or empty adUnitId was provided for rewarded video id=" + rewardedVideoAd.id,
                null
            )
            return
        }

        if (activity == null) {
            Logger.w(
                "Ads",
                "RewardedVideo applovin native callLoadRewardedVideoAd activity is null"
            )
            result.error("activity_is_null", "activity_is_null", null)
            return
        }
        Logger.d("Ads", "RewardedVideo applovin native callLoadRewardedVideoAd load")
        val adAmazonSlotId = methodCall.argument<String>("adAmazonSlotId") ?: ""

        rewardedVideoAd.load(activity!!, adUnitId, adAmazonSlotId)
        result.success(true)
    }

    private fun callShowRewardedVideoAd(
        id: Int?,
        methodCall: MethodCall,
        result: MethodChannel.Result
    ) {
        if (id == null) {
            Logger.w("Ads", "RewardedVideo applovin native callShowRewardedVideoAd lose hash id")
            result.error("no_hash_id", "show rewardedVideoAd lose hash id", null)
        }

        var rewardedVideoAd = RewardedVideoAd.getAdForId(id!!)
        if (rewardedVideoAd != null && rewardedVideoAd.status == AdStatus.LOADED) {
            val placement = methodCall.argument<String>("placement")
            result.success(rewardedVideoAd.show(placement))
            Logger.d("Ads", "RewardedVideo applovin native callShowRewardedVideoAd show")
        } else {
            Logger.w(
                "Ads",
                "RewardedVideo applovin native callShowRewardedVideoAd ad is not loaded"
            )
            result.error(
                "ad_not_loaded",
                "show failed for rewardedVideo ad, no ad was loaded",
                null
            )
        }
    }

    private fun callLoadInterstitialAd(
        id: Int?,
        methodCall: MethodCall,
        result: MethodChannel.Result
    ) {
        Logger.d("Ads", "applovin native callLoadInterstitialAd")
        if (id == null) {
            result.error("no_hash_id", "load interstitialAd lose hash id", null)
        }

        var interstitialAd = InterstitialAd.createInterstitial(id!!, channel!!)
        if (interstitialAd.status == AdStatus.LOADED) {
            Logger.w("Ads", "applovin native callLoadInterstitialAd ad is loaded")
            result.success(true) // The ad was already loaded or loading.
            return;
        }

        var adUnitId = methodCall.argument<String>("adUnitId")
        if (adUnitId.isNullOrEmpty()) {
            Logger.w("Ads", "applovin native callLoadInterstitialAd adUnitId is null or empty")
            result.error(
                "no_adunit_id",
                "a null or empty adUnitId was provided for ad id=" + interstitialAd.id,
                null
            )
            return
        }

        var adAmazonSlotId = methodCall.argument<String>("adAmazonSlotId")

        if (activity == null) {
            Logger.w("Ads", "applovin native callLoadInterstitialAd activity is null")
            result.error("activity_is_null", "activity_is_null", null)
            return
        }

        Logger.d(
            "Ads",
            "applovin native callLoadInterstitialAd load adAmazonSlotId:$adAmazonSlotId"
        )

        interstitialAd.load(activity!!, adUnitId, adAmazonSlotId)
        result.success(true)
    }

    private fun callShowInterstitialAd(
        id: Int?,
        methodCall: MethodCall,
        result: MethodChannel.Result
    ) {
        if (id == null) {
            Logger.w("Ads", "applovin native callShowInterstitialAd lose hash id")
            result.error("no_hash_id", "show interstitialAd lose hash id", null)
        }

        var interstitialAd = InterstitialAd.getAdForId(id!!)
        if (interstitialAd != null && interstitialAd.status == AdStatus.LOADED) {
            val placement = methodCall.argument<String>("placement")
            result.success(interstitialAd.show(placement))
            Logger.d("Ads", "applovin native callShowInterstitialAd show")
        } else {
            Logger.w("Ads", "applovin native callShowInterstitialAd ad is not loaded")
            result.error("ad_not_loaded", "show failed for interstitial ad, no ad was loaded", null)
        }
    }

    private fun callInterstitialAdLoaded(id: Int?, result: MethodChannel.Result) {
        if (id == null) {
            Logger.w("Ads", "applovin native callInterstitialAdLoaded lose hash id")
            result.error("no_hash_id", "is interstitialAd loaded lose hash id", null)
        }

        var interstitialAd = InterstitialAd.getAdForId(id!!)
        if (interstitialAd == null) {
            Logger.w("Ads", "applovin native callInterstitialAdLoaded ad is not loaded")
            result.error(
                "no_ad_for_id",
                "isAdLoaded failed, no add exists for interstitialAd id=$id",
                null
            )
            return
        }
        if (interstitialAd.status == AdStatus.LOADED) {
            result.success(true)
        } else {
            result.success(false)
        }
        Logger.d("Ads", "applovin native callInterstitialAdLoaded status:${interstitialAd.status}")
    }

    private fun callLoadBannerAd(id: Int?, methodCall: MethodCall, result: MethodChannel.Result) {
        Logger.d("Ads", "applovin native callLoadBannerAd")
        if (id == null) {
            result.error("no_hash_id", "load bannerAd lose hash id", null)
        }

        var adUnitId = methodCall.argument<String>("adUnitId")
        if (adUnitId.isNullOrEmpty()) {
            Logger.w("Ads", "applovin native callLoadBannerAd adUnitId is null or empty")
            result.error(
                "no_adunit_id",
                "a null or empty adUnitId was provided for ad id=$id",
                null
            )
            return
        }

        val adAmazonSlotId = methodCall.argument<String>("adAmazonSlotId")
        val placement = methodCall.argument<String>("placement")

        if (activity == null) {
            Logger.w("Ads", "applovin native callLoadBannerAd activity is null")
            result.error("activity_is_null", "activity_is_null", null)
            return
        }

        var bannerAd = BannerAd.createBanner(id!!, channel!!)

        Logger.d("Ads", "applovin native callLoadBannerAd load")
        bannerAd.load(activity!!, adUnitId, adAmazonSlotId, placement)

        result.success(true)
    }

    private fun callShowBannerAd(id: Int?, methodCall: MethodCall, result: MethodChannel.Result) {
        if (id == null) {
            Logger.w("Ads", "applovin native callShowBannerAd lose hash id")
            result.error("no_hash_id", "show bannerAd lose hash id", null)
        }

        var bannerAd = BannerAd.getAdForId(id!!)
        if (bannerAd == null || (bannerAd.status != AdStatus.LOADED && bannerAd.status != AdStatus.HIDDEN)) {
            Logger.w("Ads", "applovin native callShowBannerAd ad is not loaded ${bannerAd?.status}")
            result.error(
                "ad_not_loaded",
                "show failed for banner ad, no ad was loaded ${bannerAd?.status}",
                null
            )
            return
        }
        val anchorOffset: String? = methodCall.argument("anchorOffset")
        val horizontalCenterOffset: String? = methodCall.argument("horizontalCenterOffset")
        val anchorType: String? = methodCall.argument("anchorType")
        if (anchorOffset != null) {
            bannerAd.anchorOffset = anchorOffset!!.toDouble()
        }
        if (horizontalCenterOffset != null) {
            bannerAd.horizontalCenterOffset = horizontalCenterOffset!!.toDouble()
        }
        if (anchorType != null) {
            bannerAd.anchorType = if ("bottom" == anchorType) Gravity.BOTTOM else Gravity.TOP
        }

        if (activity == null) {
            result.error("activity_is_null", "activity_is_null", null)
            Logger.w("Ads", "applovin native callShowBannerAd activity is null")
            return
        }

        bannerAd!!.show(activity!!)
        result.success(true)
        Logger.d("Ads", "applovin native callShowBannerAd show")
    }


    private fun callUpdateOrientation(methodCall: MethodCall, result: MethodChannel.Result) {
        @ScreenOrientation
        val orientation: Int = methodCall.argument<Int>("orientation") ?: ScreenOrientation.PORTRAIT
        activity?.apply {
            BannerAd.orientationChanged(this, orientation)
        }
        result.success(true)
    }

    private fun callHideBannerAd(id: Int?, result: MethodChannel.Result) {
        if (id == null) {
            Logger.w("Ads", "applovin native callHideBannerAd no_hash_id")
            result.error("no_hash_id", "hide bannerAd lose hash id", null)
        }

        var bannerAd = BannerAd.getAdForId(id!!)
        if (bannerAd == null) {
            Logger.w("Ads", "applovin native callHideBannerAd ad_not_loaded")
            result.error("ad_not_loaded", "bannerAd is null", null)
            return
        }

        if (activity == null) {
            Logger.w("Ads", "applovin native callHideBannerAd activity_is_null")
            result.error("activity_is_null", "activity_is_null", null)
            return
        }

        bannerAd!!.hide(activity!!)
        result.success(true)
    }

    private fun callDisposeBannerAd(id: Int?, result: MethodChannel.Result) {
        if (id == null) {
            Logger.w("Ads", "applovin native callDisposeBannerAd no_hash_id")
            result.error("no_hash_id", "dispose bannerAd lose hash id", null)
        } else {
            val act = activity
            if (act == null) {
                Logger.w("Ads", "applovin native callDisposeBannerAd activity_is_null")
                result.error("activity_is_null", "activity is detached", null)
                return
            }
            val ad = BannerAd.getAdForId(id)
            if (ad != null) {
                ad.dispose(act)
                result.success(true)
            } else {
                Logger.w("Ads", "applovin native callDisposeBannerAd ad_not_found")
                result.error(
                    "ad_not_found",
                    "dispose failed for bannerAd ad, no add exists for id=$id",
                    null
                )
            }
        }
    }

    private fun callDisposeRewardedVideoAd(id: Int?, result: MethodChannel.Result) {
        if (id == null) {
            Logger.w("Ads", "applovin native callDisposeRewardedVideoAd no_hash_id")
            result.error("no_hash_id", "dispose rewardedVideoAd lose hash id", null)
        } else {
            val ad = RewardedVideoAd.getAdForId(id)
            if (ad != null) {
                ad.dispose()
                result.success(true)
            } else {
                Logger.w("Ads", "applovin native callDisposeRewardedVideoAd ad_not_found")
                result.error(
                    "ad_not_found",
                    "dispose failed for rewardedVideo ad, not found ad",
                    null
                )
            }
        }
    }

    private fun callGetRewardedAdsState(id: Int?, result: MethodChannel.Result) {
        if (id == null) {
            Logger.w("Ads", "applovin native callGetRewardedAdsState no_hash_id")
            result.error("no_hash_id", "get Rewarded STATE lose hash id", null)
        } else {
            val ad = RewardedVideoAd.getAdForId(id)
            if (ad != null) {
                result.success(ad.getState())
            } else {
                result.error(
                    "ad_not_found",
                    "get ad state for rewardedVideo ad, not found ad",
                    null
                )
            }
        }
    }

    private fun callDisposeInterstitialAd(id: Int?, result: MethodChannel.Result) {
        if (id == null) {
            Logger.w("Ads", "applovin native callDisposeInterstitialAd no_hash_id")
            result.error("no_hash_id", "dispose interstitialAd lose hash id", null)
        } else {
            val ad = InterstitialAd.getAdForId(id)
            if (ad != null) {
                ad.dispose()
                result.success(true)
            } else {
                Logger.w("Ads", "applovin native callDisposeInterstitialAd ad_not_found")
                result.error(
                    "ad_not_found",
                    "dispose failed for interstitialAd ad, not found ad",
                    null
                )
            }
        }
    }

    private fun callGetInterstitialAdsState(id: Int?, result: MethodChannel.Result) {
        if (id == null) {
            Logger.w("Ads", "applovin native callGetInterstitialAdsState no_hash_id")
            result.error("no_hash_id", "get Interstitial STATE lose hash id", null)
        } else {
            val ad = InterstitialAd.getAdForId(id)
            if (ad != null) {
                val state = ad.getState()
                Logger.d(
                    "Ads",
                    "applovin native callGetInterstitialAdsState[${ad.adUnitId}] ad.getState() = $state"
                )
                result.success(state)
            } else {
                Logger.w("Ads", "applovin native callGetInterstitialAdsState ad_not_found")
                result.error(
                    "ad_not_found",
                    "getAdState for Interstitial ad, not found ad",
                    null
                )
            }
        }
    }

    private fun callAfterAcceptPrivacy(methodCall: MethodCall, result: MethodChannel.Result) {
//    when (methodCall.argument<Boolean>("consentResult")) {
//      true -> {
//        AdRegistration.setConsentStatus(AdRegistration.ConsentStatus.EXPLICIT_YES)
//      }
//      false -> {
//        AdRegistration.setConsentStatus(AdRegistration.ConsentStatus.EXPLICIT_NO)
//      }
//      else -> {
//        AdRegistration.setConsentStatus(AdRegistration.ConsentStatus.UNKNOWN)
//      }
//    }
        Logger.i("Ads", "applovin native callAfterAcceptPrivacy")
        AppLovinPrivacySettings.setHasUserConsent(true, activity)
        result.success(true)
    }

    private fun callCheckConsentDialogStatus(result: MethodChannel.Result) {
        val appLovinSdkConfiguration = AppLovinSdk.getInstance(AdHelp.activity).configuration

        when (appLovinSdkConfiguration.consentDialogState) {
            AppLovinSdkConfiguration.ConsentDialogState.APPLIES -> {
                result.success(ConsentResult.ShouldShow)
            }

            AppLovinSdkConfiguration.ConsentDialogState.DOES_NOT_APPLY -> {
                result.success(ConsentResult.GdprNotApplies)
            }

            else -> {
                result.success(ConsentResult.Unknown)
            }
        }
    }

    private fun callHasUserConsent(result: MethodChannel.Result) {
        result.success(AppLovinPrivacySettings.hasUserConsent(activity))
    }

    private fun callOpenDebugger(result: MethodChannel.Result) {
        AppLovinSdk.getInstance(activity).showMediationDebugger()
        result.success(true)
    }

    private fun callIsTablet(result: MethodChannel.Result) {
        if (activity == null) {
            Logger.w("Ads", "applovin native callIsTablet activity_is_null")
            result.error("no attach activity", "Activity is null!", null)
        }
        val isTablet = AppLovinSdkUtils.isTablet(activity)
        result.success(isTablet)
    }

    private fun callSetDebugMode(methodCall: MethodCall, result: MethodChannel.Result) {
        if (activity == null) {
            Logger.w("Ads", "applovin native callSetDebugMode activity_is_null")
            result.error("no attach activity", "Activity is null!", null)
        }
        val debugLog = methodCall.argument<Boolean>("debug_mode") ?: false
        AppLovinSdk.getInstance(activity).settings.setVerboseLogging(debugLog)
        result.success(true)
    }

    private fun callSetKeywords(methodCall: MethodCall, result: MethodChannel.Result) {
        if (activity == null) {
            Logger.w("Ads", "applovin native callSetKeywords activity_is_null")
            result.error("no attach activity", "Activity is null!", null)
        }
        val keywords = methodCall.arguments<List<String>>()
        AppLovinSdk.getInstance(activity).targetingData.keywords = keywords
        result.success(true)
        Logger.w("Ads", "native setKeywords $keywords")
    }

    private fun callClearTargetingData(methodCall: MethodCall, result: MethodChannel.Result) {
        if (activity == null) {
            Logger.w("Ads", "applovin native callClearTargetingData activity_is_null")
            result.error("no attach activity", "Activity is null!", null)
        }
        AppLovinSdk.getInstance(activity).targetingData.clearAll()
        result.success(true)
        Logger.w("Ads", "native callClearTargetingData")
    }

    private fun callGetBannerAdSize(methodCall: MethodCall, result: MethodChannel.Result) {
        if (activity == null) {
            Logger.w("Ads", "applovin native callGetBannerAdSize activity_is_null")
            result.error("no attach activity", "Activity is null!", null)
        }
        val isTablet = AppLovinSdkUtils.isTablet(activity) // Available on Android SDK 9.6.2+
        val heightPx = AppLovinSdkUtils.dpToPx(activity, if (isTablet) 90 else 50)

        val size = mapOf(
            "width" to -1.0,
            "height" to heightPx.toDouble()
        )
        result.success(size)
        Logger.w("Ads", "native callGetBannerAdSize $size")
    }
}
