package com.gh.common.util

import android.content.Context
import android.preference.PreferenceManager
import com.gh.gamecenter.common.constant.Constants
import com.gh.gamecenter.entity.TimeEntity
import com.gh.gamecenter.common.retrofit.Response
import com.gh.gamecenter.retrofit.RetrofitManager
import com.halo.assistant.HaloApp
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers

object DeviceTokenUtils {

    // 同步服务器时间
    @JvmStatic
    @Synchronized
    fun syncServerTime(context: Context) {
        val sp = PreferenceManager.getDefaultSharedPreferences(context)
        RetrofitManager.getInstance().api.time
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : Response<TimeEntity>() {
                override fun onResponse(response: TimeEntity?) {
                    val editor = sp.edit()
                    response?.time?.let {
                        editor.putLong("server_time", it)
                        editor.putLong("client_time", System.currentTimeMillis() / 1000)
                        editor.apply()
                    }
                }
            })
    }

    @JvmStatic
    fun getLaunchType(): LunchType {
        var lunchType: LunchType? = null
        val values = PreferenceManager.getDefaultSharedPreferences(HaloApp.getInstance().application).all
        // 版本更新
        if (values.isNotEmpty()) {
            for (value in values) {
                if (value.key.contains(Constants.SP_NEW_FIRST_LAUNCH_VERSION)) {
                    lunchType = LunchType.UPDATE
                    break
                }
            }
        }
        // 首次安装
        if (lunchType == null) {
            lunchType = LunchType.FIRST
        }

        return lunchType
    }

}

enum class LunchType {
    FIRST,
    UPDATE
}
