package flutter.guru.guru_applovin_flutter

import android.app.Activity
import android.content.pm.PackageManager
import com.applovin.mediation.MaxAd
import com.applovin.sdk.AppLovinSdk
import org.json.JSONObject
import java.lang.ref.SoftReference
import java.lang.ref.WeakReference
import java.util.*
import java.util.concurrent.atomic.AtomicReference

/**
 *  Created by yaqiliu on 2020-03-06.
 */
object AdHelp {


    private val activityRef: AtomicReference<Activity> = AtomicReference(null)

    val activity: Activity?
        get() = activityRef.get()

    val appVersion: String by lazy {
        activity?.let {
            it.packageManager.getPackageInfo(it.packageName, 0).versionName
        } ?: ""
    }

    fun attach(activity: Activity) {
        this.activityRef.set(activity)
    }

    fun detach() {
        this.activityRef.set(null)
    }

    fun argumentsMap(vararg args: Any): Map<String, Any>? {
        val arguments: MutableMap<String, Any> = HashMap()
        var i = 0
        while (i < args.size) {
            arguments[args[i].toString()] = args[i + 1]
            i += 2
        }
        return arguments
    }

    fun argumentsMap(id: Int, vararg args: Any): Map<String, Any>? {
        val arguments: MutableMap<String, Any> = HashMap()
        var i = 0
        arguments["id"] = id
        while (i < args.size) {
            arguments[args[i].toString()] = args[i + 1]
            i += 2
        }
        return arguments
    }

    fun argumentsMapEx(id: Int, parameters: Map<String, Any>): Map<String, Any>? {
        val arguments: MutableMap<String, Any> = HashMap()
        arguments["id"] = id
        arguments.putAll(parameters)
        return arguments
    }

    fun toAdPayload(ad: MaxAd?): String {
        if (ad == null) {
            return ""
        }
        return try {
            val config = AppLovinSdk.getInstance(activity).configuration
            JSONObject(
                    mapOf<String, Any>(
                            "ad_platform" to "MAX",
                            "id" to (ad.creativeId ?: ""),
                            "adunit_id" to ad.adUnitId,
                            "adunit_name" to (ad.placement ?: ad.adUnitId),
                            "adunit_format" to ad.format.label,
                            "adgroup_id" to "",
                            "adgroup_name" to "",
                            "adgroup_type" to "",
                            "currency" to "USD",
                            "country" to config.countryCode,
                            "app_version" to appVersion,
                            "publisher_revenue" to ad.revenue,
                            "network_name" to (ad.networkName ?: ""),
                            "network_placement_id" to ad.networkPlacement,
                            "precision" to "publisher_defined"
                    )).toString()
        } catch (throwable: Throwable) {
            ""
        }
    }
}
