package com.adealink.weparty.room.chatroom.page.dispatchcenter

import android.annotation.SuppressLint
import android.content.Intent
import androidx.lifecycle.lifecycleScope
import com.adealink.frame.mvvm.view.viewBinding
import com.adealink.weparty.commonui.BaseFragment
import com.adealink.weparty.commonui.ext.gone
import com.adealink.weparty.commonui.ext.show
import com.adealink.weparty.room.R
import com.adealink.weparty.room.databinding.FragmentDispatchCenterRoomInfoBinding
import com.adealink.weparty.room.sdk.service.roomService
import io.trtc.tuikit.atomicxcore.api.live.LiveInfo
import io.trtc.tuikit.atomicxcore.api.live.LiveListStore
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach

class DispatchCenterRoomInfoFragment : BaseFragment(R.layout.fragment_dispatch_center_room_info) {

    private val binding by viewBinding(FragmentDispatchCenterRoomInfoBinding::bind)

    override fun initViews() {
        updateRoomInfo(roomService.joinController.joinedRoomInfo)
    }

    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
        updateRoomInfo(roomService.joinController.joinedRoomInfo)
    }

    override fun observeViewModel() {
        super.observeViewModel()
        LiveListStore.shared().liveState.currentLive.onEach { liveInfo ->
            if (liveInfo.liveID == roomService.joinController.getJoinedRoomId()) {
                updateRoomInfo(liveInfo)
            }
        }.launchIn(lifecycleScope)
    }

    @SuppressLint("SetTextI18n")
    private fun updateRoomInfo(liveInfo: LiveInfo?) {
        binding.roomCover.setImageUrl(liveInfo?.coverURL)
        binding.roomName.text = liveInfo?.liveName
        liveInfo?.liveID?.let { liveID ->
            binding.roomId.show()
            binding.roomId.text = "ID $liveID"
        } ?: let {
            binding.roomId.gone()
        }
    }

}