package com.gh.common.util

import com.gh.gamecenter.core.utils.SPUtils
import com.gh.gamecenter.common.retrofit.Response
import com.gh.gamecenter.core.utils.TimeUtils
import com.gh.gamecenter.retrofit.RetrofitManager
import io.reactivex.schedulers.Schedulers
import okhttp3.ResponseBody

/**
 * 激活信息辅助类
 */
object ActivationHelper {

    private const val HAS_SENT_ACTIVATED_INFO = "has_sent_activated_info"
    private const val SENT_ACTIVATED_INFO_TIME = "sent_activated_info_time"
    private const val HAS_SENT_RETENTION_INFO = "has_sent_retention_info"

    private var hasSentActivatedInfo = SPUtils.getBoolean(HAS_SENT_ACTIVATED_INFO, false)
    private var hasSentRetentionInfo = SPUtils.getBoolean(HAS_SENT_RETENTION_INFO, false)

    /**
     * 发送激活信息 (用于推广)
     */
    @JvmStatic
    fun sendActivationInfo() {
        if (!hasSentActivatedInfo) {
            RetrofitManager.getInstance()
                .api.postActivationInfo()
                .subscribeOn(Schedulers.io())
                .subscribe(object : Response<ResponseBody>() {
                    override fun onResponse(response: ResponseBody?) {
                        super.onResponse(response)

                        hasSentActivatedInfo = true
                        SPUtils.setBoolean(HAS_SENT_ACTIVATED_INFO, true)
                        SPUtils.setLong(SENT_ACTIVATED_INFO_TIME, System.currentTimeMillis())
                    }
                })
        }
    }

    /**
     * 发送次日留存信息 (用于推广)
     */
    @JvmStatic
    fun sendRetentionInfo() {
        if (hasSentActivatedInfo && !hasSentRetentionInfo) {
            val activateTimeMillis = SPUtils.getLong(SENT_ACTIVATED_INFO_TIME, 0)
            val currentTimeMillis = System.currentTimeMillis()

            if (!TimeUtils.isNextDay(activateTimeMillis, currentTimeMillis)) {
                return
            }

            RetrofitManager.getInstance()
                .api.postRetentionInfo()
                .subscribeOn(Schedulers.io())
                .subscribe(object : Response<ResponseBody>() {
                    override fun onResponse(response: ResponseBody?) {
                        super.onResponse(response)

                        hasSentRetentionInfo = true
                        SPUtils.setBoolean(HAS_SENT_RETENTION_INFO, true)
                    }
                })
        }
    }

}