package com.base.datarecovery.utils

import android.os.Build
import android.text.TextUtils
import androidx.annotation.RequiresApi
import com.android.installreferrer.api.InstallReferrerClient
import com.android.installreferrer.api.InstallReferrerStateListener
import com.base.datarecovery.BuildConfig
import com.base.datarecovery.ads.AdmobMaxHelper
import com.base.datarecovery.fcm.NotificationTimerManager
import com.base.datarecovery.fcm.RecoveryTimerManager
import com.base.datarecovery.help.BaseApplication
import org.json.JSONObject

/**
 * call before agree
 */
object InstallHelps {
    private val TAG = "InstallHelps"
    @RequiresApi(Build.VERSION_CODES.O)
    fun init() {

        //InstallReferrer not empty
        if (!TextUtils.isEmpty(AppPreferences.getInstance().getString("install_source", ""))) {
            if (AdmobMaxHelper.haveSpAdmobTrueMaxFalse()) {
                AdmobMaxHelper.initAdmobMaxAd()
                requestCfg(false)
            } else {
                requestCfg(true)
            }
            return
        }

        //InstallReferrer empty
        val referrerClient = InstallReferrerClient.newBuilder(BaseApplication.context).build()
        referrerClient.startConnection(object : InstallReferrerStateListener {
            @RequiresApi(Build.VERSION_CODES.O)
            override fun onInstallReferrerSetupFinished(responseCode: Int) {
                LogEx.logDebug(TAG, "responseCode=$responseCode")
                try {
                    when (responseCode) {
                        InstallReferrerClient.InstallReferrerResponse.OK -> {
                            LogEx.logDebug(TAG, "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)
                            AppPreferences.getInstance().put("referrerUrl", response.installReferrer)
                            if (listOf("gclid", "facebook", "instagram").all { !installInfo.contains(it, true) }) {
                                //自然用户
                                if (BuildConfig.DEBUG) {
                                    AppPreferences.getInstance().put("install_source", "channel")
                                } else {
                                    AppPreferences.getInstance().put("install_source", "origin")
                                }
                                LogEx.logDebug("glc", "origin user")
                            } else {
                                LogEx.logDebug("glc", "channel user")
                                //渠道用户
                                AppPreferences.getInstance().put("install_source", "channel")
                            }
                            requestCfg(true)

                        }

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

            }

            override fun onInstallReferrerServiceDisconnected() {

            }
        })
    }

    @RequiresApi(Build.VERSION_CODES.O)
    fun requestCfg(callBackAd: Boolean) {
        NewComUtils.requestCfg {
            if (callBackAd) {
                AdmobMaxHelper.initAdmobMaxAd()
            }
            if(Build.VERSION.SDK_INT < Build.VERSION_CODES.UPSIDE_DOWN_CAKE){
                val notificationSwitch=AppPreferences.getInstance().getString("notificationSwitch", "0").toInt()
                if(notificationSwitch==0){
                    val notificationTimeInterval=AppPreferences.getInstance().getString("notificationTimeInterval", "60").toInt()
                    NotificationTimerManager.getInstance()
                        .startTimer(
                            (  notificationTimeInterval * 1000).toLong(),
                            (  notificationTimeInterval * 1000).toLong()
                        )
                }

            }
            val timerStatus: Int =
                AppPreferences.getInstance().getString("timerS", "1")
                    .toIntOrNull() ?: 1
            if (timerStatus == 0) {
                RecoveryTimerManager.getInstance().stopTaskTimer()
            } else {
                val timerDelay: Int =
                    AppPreferences.getInstance().getString("timerDelay", "1")
                        .toIntOrNull() ?: 1
                val timerInterval: Int =
                    AppPreferences.getInstance().getString("timerInterval", "7")
                        .toIntOrNull() ?: 7
                if (!RecoveryTimerManager.getInstance().isTaskTimerActive) {
                    RecoveryTimerManager.getInstance().scheduleTask(
                        (timerDelay * 60 * 1000).toLong(),
                        (timerInterval * 60 * 1000).toLong()
                    )
                }
            }
        }
    }
}