package com.baijiayun.live.ui.speakpanel

import android.view.LayoutInflater
import android.view.View
import androidx.lifecycle.Observer
import com.baijiayun.bjyutils.reactivex.RxUtils
import com.baijiayun.live.ui.R
import com.baijiayun.live.ui.databinding.FragmentPadMainVideoBinding
import com.baijiayun.liveuibase.ppt.PadPPTView
import com.baijiayun.livebase.context.LPConstants
import com.baijiayun.livebase.models.LPUserModel
import com.baijiayun.livebase.models.imodels.IUserModel
import com.baijiayun.livebase.base.getViewModel
import com.baijiayun.liveuibase.databinding.BjyBaseLayoutItemVideoBinding
import com.baijiayun.liveuibase.panel.BaseSpeakFragment
import com.baijiayun.liveuibase.speaklist.Playable
import com.baijiayun.liveuibase.speaklist.Switchable
import com.baijiayun.liveuibase.speaklist.SwitchableStatus
import com.baijiayun.liveuibase.viewmodel.SpeakViewModel
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import java.util.concurrent.TimeUnit

/**
 * 1v1 学生容器(自动上台)
 */
class SingleSpeakFragment : BaseSpeakFragment() {
    private var _binding: FragmentPadMainVideoBinding? = null
    private val binding get() = _binding!!
    private val speakViewModel by lazy {
        getViewModel { SpeakViewModel(routerViewModel) }
    }

    private var timeDisposable: Disposable? = null

    private val placeholderItemBinding by lazy {
        BjyBaseLayoutItemVideoBinding.bind(LayoutInflater.from(context).inflate(R.layout.bjy_base_layout_item_video, binding.root, false))
    }
    
    override fun getLayoutId(): Int = R.layout.fragment_pad_main_video

    override fun init(view: View) {
        super.init(view)
        _binding = FragmentPadMainVideoBinding.bind(view)
    }
    override fun getSpeakContainer() = binding.root

    override fun initSuccess() {
        super.initSuccess()
        binding.root.removeAllViews()
        binding.root.addView(placeholderItemBinding.root)
        showRemoteStatus(false, LPUserModel())
        speakViewModel.singleSpeakerChange.observe(this, Observer {
            it?.let {
                showRemoteStatus(!it.first, it.second)
            }
        })

        routerViewModel.isClassStarted.observe(this, Observer {
            if (it == true) {
                enableAutoSpeak()
            }
        })
    }

    override fun showClassEnd() {
        super.showClassEnd()
        showRemoteStatus(speakViewModel.singleSpeakerChange.value?.first != true,
                speakViewModel.singleSpeakerChange.value?.second)
    }

    private fun isAutoSpeak(): Boolean {
        val roomType = routerViewModel.liveRoom.roomInfo.roomType
        return roomType == LPConstants.LPRoomType.Single || roomType == LPConstants.LPRoomType.SmallGroup || roomType == LPConstants.LPRoomType.OneOnOne
    }

    /**
     * 一对一、小班课上课学生自动举手上麦，试听不上麦
     */
    private fun enableAutoSpeak() = with(routerViewModel) {
        if (isAutoSpeak() && liveRoom.currentUser.type == LPConstants.LPUserType.Student && !liveRoom.isAudition) {
            if (liveRoom.autoOpenCameraStatus) {
                attachLocalAudio()
                if (liveRoom.autoOpenCameraStatus) {
                    timeDisposable = Observable.timer(500, TimeUnit.MILLISECONDS).observeOn(
                        AndroidSchedulers.mainThread())
                        .subscribe { attachLocalVideo() }
                }
            } else {
                attachLocalAudio()
            }
        }
    }

    private fun showRemoteStatus(isLeave: Boolean, user: IUserModel?) {
        if (isLeave) {
            placeholderItemBinding.itemStatusPlaceholderIv.setImageResource(R.drawable.base_ic_video_leave)
            placeholderItemBinding.itemStatusPlaceholderTv.text = getString(R.string.pad_leave_room_single_speaker)
        } else {
            placeholderItemBinding.itemStatusPlaceholderIv.setImageResource(R.drawable.base_ic_video_leave)
            placeholderItemBinding.itemStatusPlaceholderTv.text = getString(R.string.pad_not_onseat)
        }
        placeholderItemBinding.itemLocalSpeakerName.text = user?.name ?: ""
        placeholderItemBinding.itemLocalSpeakerName.visibility = View.VISIBLE
        placeholderItemBinding.root.visibility = View.VISIBLE
        //学生离开教室把原来在学生位置的ppt移到全屏位置
        if (isLeave && routerViewModel.ppt.pptStatus == SwitchableStatus.SpeakList) {
            routerViewModel.ppt.switchPPTVideoWithoutSync()
        }
        binding.root.removeAllViews()
        binding.root.addView(placeholderItemBinding.root)
    }

    override fun forceKeepAlive() = true

    override fun addView(child: View, index: Int, switchable: Switchable) {
        if (switchable is Playable && switchable.user.type != LPConstants.LPUserType.Student) {
            return
        }
        binding.root.removeAllViews()
        binding.root.addView(child)
    }

    override fun onDestroyView() {
        super.onDestroyView()
        RxUtils.dispose(timeDisposable)
        binding.root.removeAllViews()
        _binding = null
    }

    companion object {
        fun newInstance() = SingleSpeakFragment()
    }
}