package com.base.datarecovery.ads.max

import android.os.Bundle
import com.applovin.mediation.MaxAd
import com.applovin.mediation.MaxAdRevenueListener
import com.applovin.sdk.AppLovinSdk
import com.base.datarecovery.help.BaseApplication
import com.base.datarecovery.utils.EventUtils
import com.base.datarecovery.utils.LogEx
import com.facebook.FacebookSdk
import com.google.firebase.analytics.FirebaseAnalytics
import org.json.JSONObject

object AdMaxEvent {
    fun pullAd(ad: MaxAd?, adUnit: String, error: String? = null, reqId: String? = null, code: Int? = 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("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)
        obj.put("mediation", "applovin")
        if (error == null) {
            obj.put("status", "1")
        } else {
            obj.put("code", code)
            obj.put("errMsg", error)
            obj.put("status", "2")
        }
        EventUtils.event("ad_pull", ext = obj)
    }

    fun clickAd(ad: MaxAd?, adUnit: 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("mediation", "applovin")
        if (!adUnit.equals("nativeAd")) {
            EventUtils.event("ad_click", ext = obj)
        } else {
            EventUtils.event("big_imgad_click", ext = obj)
        }

    }

    fun showAd(ad: MaxAd?, adUnit: String, 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")
        LogEx.logDebug("glc", "from:   $activity")
        if (!adUnit.equals("nativeAd")) {
            EventUtils.event("ad_show", ext = obj)
        } else {
            EventUtils.event("big_img_show", ext = obj)
        }

    }

    private val taichiPref = FacebookSdk.getApplicationContext()
        .getSharedPreferences("TaichiTroasCache", 0)
    private val taichiSharedPreferencesEditor = taichiPref.edit()

    class EventOnPaidEventListener : MaxAdRevenueListener {
        override fun onAdRevenuePaid(ad: MaxAd) {
            LogEx.logDebug("glc", "onAdRevenuePaid")
            val params = Bundle()
            val currentImpressionRevenue: Double = ad.revenue // In USD
            val mFirebaseAnalytics = FirebaseAnalytics.getInstance(BaseApplication.context)
            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)//重新清零，开始计算
            } else {
                taichiSharedPreferencesEditor.putFloat(
                    "TaichiTroasCache",
                    currentTaichiTroasCache.toFloat()
                )
                taichiSharedPreferencesEditor.commit()
            }
            val obj = JSONObject()
            val revenue = ad.revenue
            val countryCode =
                AppLovinSdk.getInstance(BaseApplication.context).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)
//            com.base.datarecovery.utils.EventUtils.com.base.datarecovery.utils.event("ad_price", ext = obj)
        }

    }
}