package com.yidian.shenghuoquan.newscontent.utils

import android.text.TextUtils
import com.google.gson.Gson
import com.orhanobut.hawk.Hawk
import com.yidian.common.HawkConfig
import com.yidian.common.utils.EncryptUtil
import com.yidian.framework.mobile.xdiamond.SecretUtil
import com.yidian.shenghuoquan.newscontent.bean.TokenBean
import java.util.*

class AccountUtil {
    companion object {
        @Synchronized
        fun getGuestUsername(): String {
            var username = Hawk.get(HawkConfig.GuestAccountUsername, "")
            if (TextUtils.isEmpty(username)) {
                username = try {
                    val uuid = UUID.randomUUID()
                    "HG_$uuid"
                } catch (e: Exception) {
                    //做必要的保护
                    val r = Random()
                    val d = Date()
                    r.setSeed(d.time)
                    val random = r.nextInt(10000)
                    "HG_" + System.currentTimeMillis() + '-' + random
                }
            }
            return username
        }

        fun getPassword(username: String): String {
            val strLower = username.toLowerCase()
            val strMd5 = EncryptUtil.getMD5(username)
            val strTemp = strLower + strMd5
            return encryptMore(strTemp, 1000)
        }

        private fun encryptMore(str: String, count: Int): String {
            val strTemp = EncryptUtil.encryptToSHA(str)
            val num = count - 1
            return if (num > 0) {
                encryptMore(strTemp, num)
            } else {
                strTemp
            }
        }

        fun getToken(username: String, password: String): String? {
            val secret = SecretUtil.sign(username + password)
            val tokenBean = TokenBean(secret, username, password)
            val jsonString = Gson().toJson(tokenBean)
            return SecretUtil.rsaEncrypt(jsonString)
        }
    }
}