package com.adealink.weparty.call.comp

import androidx.lifecycle.LifecycleOwner
import com.adealink.frame.base.Rlt
import com.adealink.frame.base.fastLazy
import com.adealink.weparty.call.databinding.LayoutCallUserinfoBinding
import com.adealink.weparty.module.profile.ProfileModule
import com.adealink.weparty.module.profile.data.UserInfo
import com.tencent.qcloud.tuikit.tuicallkit.common.utils.peerUid
import io.trtc.tuikit.atomicxcore.api.call.CallInfo
import io.trtc.tuikit.atomicxcore.api.call.CallStore
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch

class CallUserInfoComp(
    lifecycleOwner: LifecycleOwner,
    private val binding: LayoutCallUserinfoBinding
) : BaseCallViewComponent(lifecycleOwner) {

    private val profileViewModel by fastLazy { ProfileModule.getProfileViewModel(requireActivity()) }

    override suspend fun observeCallState(scope: CoroutineScope) {
        scope.launch {
            CallStore.shared.observerState.activeCall.collect { callInfo ->
                setUserInfo(callInfo)
            }
        }
    }

    override fun loadData() {
        setUserInfo(CallStore.shared.observerState.activeCall.value)
    }

    private fun setUserInfo(callInfo: CallInfo) {
        val peerUid = callInfo.peerUid(ProfileModule.getMyUid())
        if (peerUid.isNullOrEmpty()) {
            updateUserInfo(null)
            return
        }
        profileViewModel?.pullUserInfoBy(peerUid, true)?.observe(viewLifecycleOwner) { rlt ->
            when (rlt) {
                is Rlt.Failed -> {
                    updateUserInfo(null)
                }

                is Rlt.Success -> {
                    updateUserInfo(rlt.data)
                }
            }
        }
    }

    private fun updateUserInfo(userInfo: UserInfo?) {
        binding.ivAvatar.setImageUrl(userInfo?.avatar)
        binding.tvName.text = userInfo?.nickName
    }
}