package com.adealink.weparty.room.micseat

import android.content.Intent
import android.os.Bundle
import android.view.View
import androidx.fragment.app.activityViewModels
import com.adealink.frame.mvvm.view.viewBinding
import com.adealink.weparty.commonui.BaseFragment
import com.adealink.weparty.room.R
import com.adealink.weparty.room.constant.logRoomTime
import com.adealink.weparty.room.databinding.FragmentMicSeatBinding
import com.adealink.weparty.room.micseat.defaults.BaseDefaultSeatView
import com.adealink.weparty.room.micseat.dispatcenter.DispatchCenterSeatsTemplate
import com.adealink.weparty.room.micseat.viewmodel.RoomSeatViewModel
import com.adealink.weparty.room.viewmodel.RoomViewModelFactory

class MicSeatFragment : BaseFragment(R.layout.fragment_mic_seat) {

    private val binding by viewBinding(FragmentMicSeatBinding::bind)
    private val roomSeatViewModel by activityViewModels<RoomSeatViewModel> { RoomViewModelFactory() }
    private var currentSeatsTemplate: BaseSeatsTemplate<out BaseDefaultSeatView, out BaseSeatsTemplateViewModel>? =
        null

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        logRoomTime("MicSeatFragment onViewCreated")
        switchMicSeatTemplate()
    }

    private fun switchMicSeatTemplate() {
        switchToDispatchCenter()
    }

    private fun switchToDispatchCenter() {
        if (currentSeatsTemplate is DispatchCenterSeatsTemplate) {
            return
        }
        DispatchCenterSeatsTemplate().let {
            currentSeatsTemplate = it
            childFragmentManager
                .beginTransaction()
                .replace(R.id.fragment_container_seats, it)
                .commit()
        }
    }

    fun getSeatViewByUid(uid: String): BaseSeatView? {
        if (currentSeatsTemplate?.isViewCreated() == false) {
            return null
        }
        return currentSeatsTemplate?.getSeatViewByUid(uid)
    }

    fun getSeatViewByIndex(index: Int): BaseSeatView? {
        if (currentSeatsTemplate?.isViewCreated() == false) {
            return null
        }
        return currentSeatsTemplate?.getSeatView(index)
    }

    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
        val currentTemplate = currentSeatsTemplate
        switchMicSeatTemplate()
//        if (currentTemplate == currentSeatsTemplate) {
//            //没有更换麦位模版,重置并重新加载当前麦位
//            reloadCurrentSeatsTemplate()
//        }
    }

//    private fun reloadCurrentSeatsTemplate() {
//        if (currentSeatsTemplate?.isViewCreated() == true) {
//            currentSeatsTemplate?.resetAllMicSeatViews()
//            currentSeatsTemplate?.loadData()
//        }
//    }

    companion object {
        private const val TAG = "MicSeatFragment"
    }

}