package com.adealink.weparty.im.data

import com.adealink.frame.data.json.froJsonErrorNull
import com.adealink.frame.data.json.toJsonErrorNull
import com.adealink.weparty.im.datasource.local.IMLocalService
import com.tencent.imsdk.BaseConstants
import java.io.Serializable

class UserInfo private constructor() : Serializable {
    var sdkAppId: Int = 0
    private var userId: String? = null
    private var userSig: String? = null
    private var autoLogin = false
    var isDebugLogin: Boolean = false
        set(debugLogin) {
            field = debugLogin
            setUserInfo(this)
        }
    private var lastLoginCode = BaseConstants.ERR_SUCC

    fun setUserInfo(info: UserInfo?) {
        IMLocalService.loginUserInfo = toJsonErrorNull(info) ?: ""
    }

    fun getUserSig(): String? {
        return this.userSig
    }

    fun setUserSig(userSig: String?) {
        this.userSig = userSig
        setUserInfo(this)
    }

    fun getUserId(): String? {
        return this.userId
    }

    fun setUserId(userId: String?) {
        this.userId = userId
        setUserInfo(this)
    }

    fun isAutoLogin(): Boolean {
        return this.autoLogin
    }

    fun setAutoLogin(autoLogin: Boolean) {
        this.autoLogin = autoLogin
        setUserInfo(this)
    }

    fun getLastLoginCode(): Int {
        return lastLoginCode
    }

    fun setLastLoginCode(lastLoginCode: Int) {
        this.lastLoginCode = lastLoginCode
        setUserInfo(this)
    }

    fun cleanUserInfo() {
        sdkAppId = 0
        userId = ""
        userSig = ""
        autoLogin = false
        lastLoginCode = BaseConstants.ERR_SUCC
        setUserInfo(this)
    }

    companion object {
        private const val PER_USER_MODEL = "per_user_model"

        private var sUserInfo: UserInfo? = null

        @JvmStatic
        @get:Synchronized
        val loginUserInfo: UserInfo
            get() {
                var loginUserInfo: UserInfo? = null
                if (sUserInfo == null) {
                    val userInfoStr = IMLocalService.loginUserInfo
                    loginUserInfo = if (userInfoStr.isNotEmpty()) {
                        froJsonErrorNull(userInfoStr, UserInfo::class.java)
                    } else {
                        UserInfo()
                    }
                    sUserInfo = loginUserInfo
                }
                return loginUserInfo ?: UserInfo()
            }
    }
}
