package com.gh.common.util

import android.content.Context
import android.os.Environment
import android.preference.PreferenceManager
import com.gh.gamecenter.common.exposure.meta.MetaUtil
import com.gh.gamecenter.BuildConfig
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 com.lightgame.utils.Utils
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import java.io.File

object DeviceTokenUtils {

    const val DEVICE_ID = "uuid"

    // 同步服务器时间
    @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(readOnly: Boolean = false): LunchType {
        var lunchType: LunchType? = null
        val values = PreferenceManager.getDefaultSharedPreferences(HaloApp.getInstance().application).all
        // 版本更新
        if (values.isNotEmpty()) {
            for (value in values) {
                if (value.key.contains("isNewFirstLaunchV")) {
                    lunchType = LunchType.UPDATE
                    break
                }
            }
        }
        // 再次重装
        if (lunchType == null && !getDeviceId().isNullOrEmpty()) {
            lunchType = LunchType.AGAIN
        }
        // 首次安装
        if (lunchType == null) {
            lunchType = LunchType.FIRST
        }
        // 保存deviceId
        var deviceId = MetaUtil.getIMEI()
        if (deviceId.isNullOrEmpty()) {
            deviceId = Utils.getTime(HaloApp.getInstance().application).toString()
        }

        if (!readOnly) {
            setDeviceId(deviceId)
        }

        return lunchType
    }

    private fun getDeviceFileList(): List<File> {
        val sdCardDir = Environment.getExternalStorageDirectory()
        val fileList: MutableList<File> = ArrayList()
        fileList.add(File(sdCardDir.path + "/gh-uuid/$DEVICE_ID"))
        fileList.add(File(sdCardDir.path + "/system/$DEVICE_ID"))
        fileList.add(File(sdCardDir.path + "/data/$DEVICE_ID"))
        return fileList
    }


    @Synchronized
    private fun setDeviceId(deviceId: String) {
        //将deviceId存到sp
        val sp = PreferenceManager.getDefaultSharedPreferences(HaloApp.getInstance().application)
        val edit = sp.edit()
        edit.putString(DEVICE_ID, deviceId)
        edit.apply()
        Utils.log("saveDeviceId", "保存成功SP")

        //将deviceId存到SD卡
        for (file in getDeviceFileList()) {
            try {
                val parentFile = file.parentFile
                if (!parentFile.exists()) parentFile.mkdirs()
                file.writeText(deviceId)
                Utils.log("saveDeviceId", "保存成功SDCard目录为：${file.path}")
            } catch (e: Exception) {
                Utils.log("保存u${DEVICE_ID}到SDCard异常${file.path} " + e.toString())
                e.printStackTrace()
            }
        }
    }

    private fun getDeviceId(): String? {
        val sp = PreferenceManager.getDefaultSharedPreferences(HaloApp.getInstance().application)
        var deviceId = sp.getString(DEVICE_ID, null)
        if (deviceId.isNullOrEmpty()) {
            val fileList = getDeviceFileList()
            for (file in fileList) {
                if (file.exists()) {
                    try {
                        deviceId = file.readText()
                        Utils.log("getDeviceId", "获取成功DataFile$DEVICE_ID")
                        return deviceId
                    } catch (e: Exception) {
                        e.printStackTrace()
                    }
                }
            }
        }
        if (BuildConfig.DEBUG) {
            Utils.log("getDeviceId", "获取成功SP$DEVICE_ID")
        }
        return deviceId
    }

}

enum class LunchType {
    FIRST,
    UPDATE,
    AGAIN
}
