package com.dlc.eboard.ui.monitor

import android.content.Intent
import android.os.Bundle
import android.view.View
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import cn.nodemedia.NodePlayer
import cn.nodemedia.NodePlayerView
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.module.LoadMoreModule
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.dlc.eboard.LabApp
import com.dlc.eboard.R
import com.dlc.eboard.common.CommonUtils
import com.dlc.eboard.databinding.ActivityMonitorListBinding
import com.dlc.eboard.ui.common.BaseCountDownRefreshActivity
import com.dlc.eboard.ui.widget.NavViewCompat
import com.dlc.eboard.ui.widget.TitleBar
import com.rc.core.ui.widget.decoration.GridSpacingItemDecoration
import com.rc.core.util.DeviceUtils
import com.rc.httpcore.client.ApiRepository
import com.rc.httpcore.vo.response.MonitorVo
import io.reactivex.disposables.Disposable

/**
 * 视频监控
 *
 * @author ReiChin_
 */
class MonitorListActivity :
    BaseCountDownRefreshActivity<MonitorVo, ActivityMonitorListBinding>() {

    override val mSrlRefresh: SwipeRefreshLayout by lazy { viewBinding.swipeRefreshLayout }
    override val mRvContent: RecyclerView by lazy { viewBinding.recyclerView }
    override val mAdapter: BaseQuickAdapter<MonitorVo, BaseViewHolder>
            by lazy { MonitorAdapter() }

    override val mTitleBar: TitleBar by lazy { viewBinding.titleBar }
    override val mNavView: NavViewCompat by lazy { viewBinding.navView }

    override fun createViewBinding() = ActivityMonitorListBinding.inflate(layoutInflater)

    override fun initViews(savedInstanceState: Bundle?) {
        super.initViews(savedInstanceState)
        mAdapter.addChildClickViewIds(R.id.fullScreen)
    }

    override fun createLayoutManager(): RecyclerView.LayoutManager {
        return GridLayoutManager(this, 2)
    }

    override fun createItemDecoration(): RecyclerView.ItemDecoration {
        return GridSpacingItemDecoration(
            2,
            DeviceUtils.dip2px(this, 27f),
            DeviceUtils.dip2px(this, 36f), false
        )
    }

    override fun onLoadMore() {
        mAdapter.loadMoreModule.loadMoreEnd(false)
    }

    override fun queryData(): Disposable? {
        if (null == LabApp.sLabConfig) {
            showToast("暂无实验室信息，即将重新获取")
            CommonUtils.restartApp(this)
            return null
        }

        return ApiRepository.cameraBySubjectId(LabApp.sLabConfig!!.labId)
            .subscribe({ data ->
                dispatchLoadDataSuccess(data)
            }, { throwable ->
                dispatchLoadDataFailure(throwable)
            })
    }

    override fun onItemChildClick(adapter: BaseQuickAdapter<*, *>, view: View, position: Int) {
        val item = mAdapter.getItem(position)
        val intent = Intent(this, MonitorFullScreenActivity::class.java)
        intent.putExtra("data", item)
        startActivity(intent)
    }

    override fun enabledBackCountDown() = true

    override fun enabledLogoutCountDown() = true

    override fun onDestroy() {
        (mAdapter as MonitorAdapter).releaseNodePlayer()
        super.onDestroy()
    }

}

private class MonitorAdapter :
    BaseQuickAdapter<MonitorVo, BaseViewHolder>(R.layout.item_monitor),
    LoadMoreModule {

    private val mPlayerMap = mutableMapOf<String?, NodePlayer>()

    override fun setNewInstance(list: MutableList<MonitorVo>?) {
        if (list === this.data) return

        if (list.isNullOrEmpty()) {
            releaseNodePlayer()
        } else {
            list.forEach {
                val key = CommonUtils.stringToMD5(it.fmp4)
                val nodePlayer = mPlayerMap[key]
                if (null != nodePlayer) {
                    nodePlayer.stop()
                    nodePlayer.release()
                } else {
                    mPlayerMap[key]= NodePlayer(context)
                }
            }
        }
        super.setNewInstance(list)
    }

    fun releaseNodePlayer() {
        mPlayerMap.values.forEach { player ->
            player.stop()
            player.release()
        }
    }

    override fun convert(holder: BaseViewHolder, item: MonitorVo) {
        initMonitor(holder.getView(R.id.monitor), item.fmp4)
    }

    private fun initMonitor(nodePlayerView: NodePlayerView, rtspUrl: String) {
        // 设置渲染器类型
        nodePlayerView.renderType = NodePlayerView.RenderType.SURFACEVIEW
        // 设置视频画面缩放模式
        nodePlayerView.setUIViewContentMode(NodePlayerView.UIViewContentMode.ScaleToFill)

        val key = CommonUtils.stringToMD5(rtspUrl)
        val nodePlayer = mPlayerMap[key]!!
        // 设置播放视图
        nodePlayer.setPlayerView(nodePlayerView)
        // 设置RTSP流使用的传输协议,支持的模式有:
        nodePlayer.setRtspTransport(NodePlayer.RTSP_TRANSPORT_TCP)
        nodePlayer.setInputUrl(rtspUrl)
//        nodePlayer.setInputUrl("rtsp://192.168.1.10:554/user=admin_password=nTBCS19C_channel=1_stream=0.sdp?real_stream")
        // 设置视频是否开启
        nodePlayer.setVideoEnable(true)
        nodePlayer.setBufferTime(0)
        nodePlayer.setMaxBufferTime(0)
        nodePlayer.start()
    }

}