package com.base.filerecoveryrecyclebin.utils

import com.android.installreferrer.api.InstallReferrerClient
import com.android.installreferrer.api.InstallReferrerStateListener
import com.base.filerecoveryrecyclebin.help.BaseApplication
import org.json.JSONObject

/**
 * call before agree
 */
object InstallHelps {
    fun init() {
        val referrerClient = InstallReferrerClient.newBuilder(BaseApplication.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())
                            EventUtils.event("install_referrer", ext = obj, isSingleEvent = true)
                        }

                        else -> {
                            EventUtils.event("install_referrer_error")
                        }
                    }
                } catch (_: Exception) {
                    EventUtils.event("install_referrer_error")
                }

            }

            override fun onInstallReferrerServiceDisconnected() {

            }
        })
    }
}