package com.dumpster.cleaner.business.ads.applovin

import android.os.Bundle
import com.applovin.mediation.MaxAd
import com.applovin.mediation.MaxAdRevenueListener
import com.applovin.mediation.MaxError
import com.applovin.sdk.AppLovinSdk
import com.dumpster.cleaner.MyApplication
import com.dumpster.cleaner.business.ads.AdEvent
import com.dumpster.cleaner.business.ads.taichiPref
import com.dumpster.cleaner.business.ads.taichiSharedPreferencesEditor
import com.dumpster.cleaner.business.helper.EventUtils
import com.dumpster.cleaner.utils.LogEx.logDebug
import com.facebook.appevents.AppEventsConstants
import com.facebook.appevents.AppEventsLogger
import com.google.firebase.analytics.FirebaseAnalytics
import org.json.JSONObject


class AdMaxEvent : AdEvent {

    override val TAG: String = "AdMaxEvent"

    constructor(adUnit: String, from: String) : super() {
        this.adUnit = adUnit
        this.from = from
    }

    fun pullAd(
        ad: MaxAd?,
        error: MaxError? = null
    ) {
        val obj = JSONObject()
        obj.put("UnitId", ad?.adUnitId)
        obj.put("ad_unit", adUnit)
        obj.put(
            "creativeId",
            ad?.creativeId
        )
        obj.put("req_id", reqId)
        obj.put("from", from)
        obj.put("status", if (ad == null) "0" else "1")
        obj.put("networkname", ad?.networkName)
        obj.put("placement", ad?.placement)
        obj.put("networkplacement", ad?.networkPlacement)
        obj.put("latency", ad?.requestLatencyMillis)
        obj.put("valueMicros", ad?.revenue)
        if (error == null) {
            obj.put("status", "1")
        } else {
            obj.put("errMsg", error)
            obj.put("status", "2")
        }
        EventUtils.event("ad_pull", ext = obj)
        logDebug(TAG, "ad_pull $obj")
    }

    fun clickAd(ad: MaxAd?) {

        val obj = JSONObject()
        obj.put("UnitId", ad?.adUnitId)
        obj.put("ad_unit", adUnit)
        obj.put(
            "creativeId",
            ad?.creativeId
        )
        obj.put("networkname", ad?.networkName)
        obj.put("placement", ad?.placement)
        obj.put("networkplacement", ad?.networkPlacement)
        obj.put("latency", ad?.requestLatencyMillis)
        obj.put("valueMicros", ad?.revenue)
        if (!adUnit.equals("nativeAd")) {
            EventUtils.event("ad_click", ext = obj)
        } else {
            EventUtils.event("ad_click", ext = obj)
        }

    }

    fun showAd(ad: MaxAd?, activity: String?) {
        val obj = JSONObject()
        obj.put("UnitId", ad?.adUnitId)
        obj.put("ad_unit", adUnit)
        obj.put(
            "creativeId",
            ad?.creativeId
        )
        obj.put("networkname", ad?.networkName)
        obj.put("placement", ad?.placement)
        obj.put("networkplacement", ad?.networkPlacement)
        obj.put("latency", ad?.requestLatencyMillis)
        obj.put("valueMicros", ad?.revenue)
        obj.put("from", activity)
        obj.put("mediation", "applovin")
        if (adUnit != "nativeAd") {
            EventUtils.event("ad_show", ext = obj)
        } else {
            EventUtils.event("ad_show", ext = obj)
        }

    }


    class EventOnPaidEventListener : MaxAdRevenueListener {
        override fun onAdRevenuePaid(ad: MaxAd) {
            val params = Bundle()
            val currentImpressionRevenue: Double = ad.revenue // In USD
            val mFirebaseAnalytics = FirebaseAnalytics.getInstance(MyApplication.appContext)
            params.putString(FirebaseAnalytics.Param.AD_PLATFORM, "appLovin")
            params.putString(FirebaseAnalytics.Param.AD_SOURCE, ad.networkName)
            params.putString(FirebaseAnalytics.Param.AD_FORMAT, ad.format.getDisplayName())
            params.putString(FirebaseAnalytics.Param.AD_UNIT_NAME, ad.adUnitId)
            params.putDouble(FirebaseAnalytics.Param.VALUE, currentImpressionRevenue)
            params.putString(FirebaseAnalytics.Param.CURRENCY, "USD")
            mFirebaseAnalytics.logEvent(FirebaseAnalytics.Event.AD_IMPRESSION, params)
            mFirebaseAnalytics.logEvent("Ad_Impression_Revenue", params)
            val previousTaichiTroasCache = taichiPref.getFloat("TaichiTroasCache", 0f)
            val currentTaichiTroasCache = previousTaichiTroasCache + currentImpressionRevenue
            if (currentTaichiTroasCache >= 0.01) {
                val roasbundle = Bundle()
                roasbundle.putDouble(FirebaseAnalytics.Param.VALUE, currentTaichiTroasCache)
                roasbundle.putString(FirebaseAnalytics.Param.CURRENCY, "USD")///(Required)tROAS事件必须
                mFirebaseAnalytics.logEvent("Total_Ads_Revenue_001", roasbundle) // 给Taichi用
                taichiSharedPreferencesEditor.putFloat("TaichiTroasCache", 0f)//重新清零，开始计算

                val logger = AppEventsLogger.newLogger(MyApplication.appContext)
                val parameters = Bundle()
                parameters.putString(AppEventsConstants.EVENT_PARAM_CURRENCY, "USD")
                logger.logEvent("ad_value", currentTaichiTroasCache, parameters)
            } else {
                taichiSharedPreferencesEditor.putFloat(
                    "TaichiTroasCache",
                    currentTaichiTroasCache.toFloat()
                )
                taichiSharedPreferencesEditor.commit()
            }
            val obj = JSONObject()
            val revenue = ad.revenue
            val countryCode =
                AppLovinSdk.getInstance(MyApplication.appContext).configuration.countryCode
            val networkName = ad.networkName
            val adUnitId = ad.adUnitId
            val adFormat = ad.format
            val placement = ad.placement
            val networkPlacement = ad.networkPlacement
            obj.put("valueMicros", revenue)
            obj.put("currencyCode", countryCode)
            obj.put("adUnitId", adUnitId)
            obj.put("networkName", networkName)
            obj.put("adFormat", adFormat)
            obj.put("placement", placement)
            obj.put("networkPlacement", networkPlacement)
            EventUtils.event("ad_price", ext = obj)
        }
    }

}