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.constant.CALL_BG_BLUR_SIZE
import com.adealink.weparty.call.databinding.LayoutCallBgBinding
import com.adealink.weparty.commonui.BaseViewComponent
import com.adealink.weparty.module.profile.ProfileModule
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.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
import kotlinx.coroutines.supervisorScope

class BgComp(
    lifecycleOwner: LifecycleOwner,
    private val bgLayoutBinding: LayoutCallBgBinding
) : BaseViewComponent(lifecycleOwner) {

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

    private var subscribeStateJob: Job? = null

    override fun observeViewModel() {
        super.observeViewModel()
        subscribeStateJob = CoroutineScope(Dispatchers.Main).launch {
            supervisorScope {
                launch {
                    CallStore.shared.observerState.activeCall.collect { callInfo ->
                        setBgAvatarUrl(callInfo)
                    }
                }
            }
        }
    }

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

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

                is Rlt.Success -> {
                    bgLayoutBinding.ivBg.setImageUrl(
                        rlt.data.avatar,
                        CALL_BG_BLUR_SIZE
                    )
                }
            }
        }
    }


    override fun onDestroy() {
        super.onDestroy()
        subscribeStateJob?.cancel()
    }
}