package com.adealink.weparty.playmate.list.comp

import androidx.lifecycle.LifecycleOwner
import com.adealink.frame.base.Rlt
import com.adealink.frame.mvvm.viewmodel.activityViewModels
import com.adealink.frame.router.Router
import com.adealink.frame.util.onClick
import com.adealink.weparty.commonui.BaseViewComponent
import com.adealink.weparty.commonui.ext.show
import com.adealink.weparty.commonui.toast.util.showToast
import com.adealink.weparty.module.room.Room
import com.adealink.weparty.module.room.data.toEnterRoomInfo
import com.adealink.weparty.playmate.databinding.LayoutPlaymateDispatchRoomBinding
import com.adealink.weparty.playmate.list.viewmodel.PlaymateRoomViewModel

class PlaymateDispatchRoomComp(
    lifecycleOwner: LifecycleOwner,
    val binding: LayoutPlaymateDispatchRoomBinding,
) : BaseViewComponent(lifecycleOwner) {

    private val roomViewModel by activityViewModels<PlaymateRoomViewModel>()

    override fun initViews() {
        super.initViews()
        binding.root.onClick {
            goRoom()
        }
    }

    override fun observeViewModel() {
        super.observeViewModel()
        roomViewModel.roomAvailableLD.observe(viewLifecycleOwner) {
            binding.root.show(it)
        }
    }

    override fun onResume() {
        super.onResume()
        roomViewModel.checkRoomAvailable()
    }

    private fun goRoom() {
        showLoading()
        roomViewModel.getAvailableRoomId().observe(viewLifecycleOwner) { rlt ->
            dismissLoading()
            when (rlt) {
                is Rlt.Failed -> {
                    showToast(rlt)
                }

                is Rlt.Success -> {
                    val act = activity ?: return@observe
                    Router.build(act, Room.Room.PATH)
                        .putExtra(Room.Room.EXTRA_ENTER_ROOM_INFO, rlt.data.toEnterRoomInfo())
                        .start()
                }
            }
        }
    }
}