package com.ritoq.quickphone.business.helper

import android.content.Context
import com.adjust.sdk.Adjust
import com.adjust.sdk.AdjustConfig
import com.adjust.sdk.LogLevel
import com.ritoq.quickphone.BuildConfig
import com.ritoq.quickphone.GlobalConfig
import com.ritoq.quickphone.business.helper.InstallHelps.installSource
import com.ritoq.quickphone.business.helper.NewComUtils.requestCfg
import com.ritoq.quickphone.utils.AppPreferences
import com.ritoq.quickphone.utils.LogEx


object AdjustUtils {

    private val TAG = "AdjustUtils"

    /**
     * origin 走 应用配置渠道
     * channel 走 facebook渠道
     *
     */
    fun getUserSource(): String {

        if (BuildConfig.DEBUG) {
            return "channel"
        }

        var source = "origin"
        if (adJustInstallSource == "channel") {
            source = "channel"
            return source
        } else {
            if (installSource == "channel") {
                source = "channel"
            }
        }
        return source
    }

    //用户来源
    var adJustInstallSource = ""
        get() {
            return AppPreferences.getInstance().getString("adJustInstallSource", field)
        }
        set(value) {
            field = value
            AppPreferences.getInstance().put("adJustInstallSource", value, true)
        }


    fun initAdjust(context: Context) {

        val environment = if (BuildConfig.DEBUG) {
            AdjustConfig.ENVIRONMENT_SANDBOX
        } else {
            AdjustConfig.ENVIRONMENT_PRODUCTION
        }


        val config = AdjustConfig(context, GlobalConfig.ADJUST_TOKEN, environment).apply {
            setLogLevel(LogLevel.ERROR)
            // 设置归因监听
            setOnAttributionChangedListener { attribution ->
                val network = attribution.network

                val isChannel = !network.isNullOrEmpty() && !network.contains("Organic", true)

                adJustInstallSource = if (isChannel) "channel" else "origin"

                LogEx.logDebug(TAG, "network=$network isChannel=$isChannel")

                requestCfg(true)
            }

        }

        LogEx.logDebug(TAG, "initSdk")
        Adjust.initSdk(config)
    }
}