package com.base.superfilemanager.helps

import com.android.installreferrer.api.InstallReferrerClient
import com.android.installreferrer.api.InstallReferrerStateListener
import org.json.JSONObject

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())
                            EventHelper.event("install_referrer", ext = obj, isSingleEvent = true)
                        }

                        else -> {
                            EventHelper.event("install_referrer_error", isSingleEvent = true)
                        }
                    }
                } catch (_: Exception) {
                    EventHelper.event("install_referrer_error", isSingleEvent = true)
                }

            }

            override fun onInstallReferrerServiceDisconnected() {

            }
        })
    }
}