package com.tencent.qcloud.tuicore.calling.login

import android.content.Context
import android.util.Log
import com.blankj.utilcode.util.ToastUtils
import com.tencent.imsdk.v2.*
import com.tencent.qcloud.tuicore.TUILogin
import com.tencent.qcloud.tuicore.calling.basic.UserModel
import com.tencent.qcloud.tuicore.calling.basic.UserModelManager
import com.tencent.qcloud.tuicore.calling.trtccalling.TUICallingImpl
import java.util.*


/**
 * TUILogin
 * 登录工具类
 * */
class LoginTUI {

    companion object {
        private const val TAG = "LoginTUI"

        fun login(context: Context, userModel: UserModel) {
            // 初始化并登录
            TUICallingImpl.sharedInstance(context)
            val config = V2TIMSDKConfig()
            config.logLevel = V2TIMSDKConfig.V2TIM_LOG_DEBUG
            TUILogin.init(context, userModel.appId, null, object : V2TIMSDKListener() {
                override fun onKickedOffline() {}
                override fun onUserSigExpired() {}
            })
            TUILogin.login(userModel.userId, userModel.userSig, object : V2TIMCallback {
                override fun onError(code: Int, msg: String) {
                    ToastUtils.showLong("登录IM失败，所有功能不可用[%d]%s", code, msg)
                    Log.d(TAG, "login fail code: $code msg:$msg")
                }

                override fun onSuccess() {
                    Log.d(TAG, "login onSuccess")
                    userInfo
                }
            })
        }

        //先查询用户是否存在
        private val userInfo: Unit
            private get() {
                val manager = UserModelManager.getInstance()
                val userModel = manager.userModel
                //先查询用户是否存在
                val userIdList: MutableList<String> = ArrayList()
                userIdList.add(userModel.userId)
                Log.d(TAG, "setUserInfo: userIdList = $userIdList")

                V2TIMManager.getInstance()
                    .getUsersInfo(
                        userIdList,
                        object : V2TIMValueCallback<List<V2TIMUserFullInfo>?> {
                            override fun onError(code: Int, msg: String) {
                                Log.e(TAG, "get group info list fail, code:$code msg: $msg")
                            }

                            override fun onSuccess(resultList: List<V2TIMUserFullInfo>?) {
                                if (resultList == null || resultList.isEmpty()) {
                                    return
                                }
                            }
                        })
            }
    }
}