package com.aiosman.ravenow.utils

import io.openim.android.sdk.OpenIMClient
import io.openim.android.sdk.listener.OnBase
import io.openim.android.sdk.models.UserInfo
import io.openim.android.sdk.models.UserInfoReq
import kotlin.coroutines.suspendCoroutine

object TrtcHelper {
    suspend fun loadUnreadCount(): Long {
        return suspendCoroutine { continuation ->
            OpenIMClient.getInstance().conversationManager
                .getTotalUnreadMsgCount(object : OnBase<String> {
                    override fun onSuccess(data: String?) {
                        // OpenIM 返回的是字符串格式的数字
                        val count = data?.toLongOrNull() ?: 0L
                        continuation.resumeWith(Result.success(count))
                    }

                    override fun onError(code: Int, error: String?) {
                        continuation.resumeWith(Result.failure(Exception("Error $code: $error")))
                    }
                })
        }
    }

    suspend fun updateTrtcProfile(
        avatar: String?,
        nickName: String?
    ) {
        val infoReq =  UserInfoReq()
        nickName?.let { infoReq.nickname = it }
        avatar?.let { infoReq.faceURL = it }
        return suspendCoroutine { continuation ->
            //(OnBase<String> base, UserInfoReq userInfoReq
            OpenIMClient.getInstance().userInfoManager.setSelfInfo(object : OnBase<String> {
                override fun onError(code: Int, error: String?) {
                    continuation.resumeWith(Result.failure(Exception("Error $code: $error")))
                }

                override fun onSuccess(data: String?) {
                    continuation.resumeWith(Result.success(Unit))
                }
            },infoReq)
        }
    }
}