package com.swiftcleaner.chovey.business

import com.android.installreferrer.api.InstallReferrerClient
import com.android.installreferrer.api.InstallReferrerStateListener
import com.swiftcleaner.chovey.CleanApplication
import com.swiftcleaner.chovey.GlobalConfig.KEY_REFERRER
import com.swiftcleaner.chovey.business.push.NotCleanTimer
import com.swiftcleaner.chovey.business.push.PushTimer
import com.swiftcleaner.chovey.util.SPUtils
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.launch
import org.json.JSONObject

object InstallReferrerUtils {

    fun init() {
        MainScope().launch(Dispatchers.IO) {
            updateInstallReferrer()
        }
    }

    private fun updateInstallReferrer() {
        val referrerClient = InstallReferrerClient.newBuilder(CleanApplication.context).build()
        referrerClient.startConnection(object : InstallReferrerStateListener {
            override fun onInstallReferrerSetupFinished(responseCode: Int) {
                try {
                    when (responseCode) {
                        InstallReferrerClient.InstallReferrerResponse.OK -> {
                            val response = referrerClient.installReferrer
                            val installInfo = response.installReferrer
                            val obj = JSONObject()
                            obj.put("referrerUrl", response.installReferrer)
                            obj.put("referrerClickTime", response.referrerClickTimestampSeconds)
                            obj.put("appInstallTime", response.installBeginTimestampSeconds)
                            obj.put("instantExperienceLaunched", installInfo.toString())
                            SPUtils.getInstance().put(KEY_REFERRER, response.installReferrer)
                            EventUtils.event("install_referrer", ext = obj)
                            if (listOf(
                                    "gclid",
                                    "facebook",
                                    "instagram"
                                ).all { !installInfo.contains(it, true) }
                            ) {
                                //自然用户
                                SPUtils.getInstance().put("install_source", "origin")
                            } else {
                                //渠道用户
                                SPUtils.getInstance().put("install_source", "channel")
                            }
                        }
                        else -> {
                            EventUtils.event("install_referrer_error")
                        }
                    }
                    getHttpConfig()
                } catch (_: Exception) {
                    EventUtils.event("install_referrer_error")
                    getHttpConfig()
                }
            }

            override fun onInstallReferrerServiceDisconnected() {
            }

        })
    }

    private fun getHttpConfig() {
        ConfigUtils.requestConfig {
            val timerStatus = SPUtils.getInstance().getInt("timerStatus", 0)
            if (timerStatus == 1) {
                val timerDelay = SPUtils.getInstance().getInt("timerDelay", 3)
                val timerInterval = SPUtils.getInstance().getInt("timerInterval", 7)
                PushTimer.start(
                    timerDelay * 60 * 1000L,
                    timerInterval * 60 * 1000L
                )
//                NotCleanTimer.start(
//                    timerDelay * 60 * 1000L,
//                    timerInterval * 60 * 1000L
//                )
            }
        }
    }
}