package com.gh.gamecenter.gamedetail.video

import android.graphics.Rect
import android.os.Handler
import android.os.Looper
import android.view.View
import androidx.recyclerview.widget.RecyclerView
import com.gh.gamecenter.common.constant.Constants
import com.gh.gamecenter.common.utils.NetworkUtils
import com.gh.gamecenter.core.utils.MD5Utils
import com.gh.gamecenter.core.utils.SPUtils
import com.gh.gamecenter.home.video.ScrollCalculatorHelper
import com.gh.gamecenter.video.detail.CustomManager
import com.halo.assistant.HaloApp

class GameDetailScrollCalculatorHelper(val listRv: RecyclerView, private val playId: Int, private val rangeTop: Int) {
    private var firstVisible = -1
    private var lastVisible = 0
    private var runnable: PlayRunnable? = null
    private val playHandler = Handler(Looper.getMainLooper())
    var currentPlayer: TopVideoView? = null

    fun onScrollStateChanged(firstVisibleItem: Int, lastVisibleItem: Int, scrollState: Int) {
        if (scrollState == RecyclerView.SCROLL_STATE_IDLE) {
            firstVisible = firstVisibleItem
            lastVisible = lastVisibleItem
            stopIfNeeded()
            playVideo(listRv)
        }
    }

    //判断player是否划出了屏幕，划出了屏幕则需要释放
    private fun stopIfNeeded() {
        if (currentPlayer != null) {
            val (playerLeft, playerTop) = IntArray(2).apply { currentPlayer!!.getLocationOnScreen(this) }
            if (playerLeft == 0 && playerTop == 0) {
                //保存进度
                val currentScheduler = currentPlayer?.currentPositionWhenPlaying?.toLong() ?: 0L
                ScrollCalculatorHelper.savePlaySchedule(
                    MD5Utils.getContentMD5(currentPlayer?.getUrl()),
                    currentScheduler
                )
                currentPlayer?.initUIState()
//                currentPlayer?.resetDetailMask()
                currentPlayer = null
                runnable?.let { playHandler.removeCallbacks(it) }
            }
        }
    }

    fun release() {
        if (currentPlayer != null) {
            val currentScheduler = currentPlayer?.currentPositionWhenPlaying?.toLong() ?: 0L
            ScrollCalculatorHelper.savePlaySchedule(MD5Utils.getContentMD5(currentPlayer?.getUrl()), currentScheduler)
            CustomManager.releaseAllVideos(currentPlayer?.getKey())
            runnable?.let { playHandler.removeCallbacks(it) }
//            currentPlayer?.resetDetailMask()
            currentPlayer = null
        }
    }

    private fun playVideo(view: RecyclerView?) {
        if (view == null) return
        val layoutManager = view.layoutManager
        var gsyBaseVideoPlayer: TopVideoView
        for (i in firstVisible until lastVisible + 1) {
            if (layoutManager == null) return

            val child = listRv.findViewHolderForAdapterPosition(i)?.itemView
            val player: View? = child?.findViewById(playId)

            if (player == null || player.visibility != View.VISIBLE || player !is TopVideoView) continue

            val rect = Rect()
            player.getLocalVisibleRect(rect)
            val width = player.width
            val height = player.height
            if (rect.left == 0 && rect.right == width && rect.top == 0 && rect.bottom == height) {
                gsyBaseVideoPlayer = player
                if (runnable != null) {
                    playHandler.removeCallbacks(runnable!!)
                    runnable = null
                }
                if (currentPlayer == gsyBaseVideoPlayer) return

                val screenPosition = IntArray(2)
                gsyBaseVideoPlayer.getLocationInWindow(screenPosition)
                val rangePosition = screenPosition[1]
                if (rangePosition >= rangeTop) {
                    runnable?.let { playHandler.removeCallbacks(it) }
                    runnable = PlayRunnable(gsyBaseVideoPlayer)
                    if (currentPlayer != null) {
                        currentPlayer?.initUIState()
//                        currentPlayer?.resetDetailMask()
                    }
                    //降低频率
                    playHandler.postDelayed(runnable!!, 100)
                    break
                }
            }
        }
    }

    private inner class PlayRunnable(var videoView: TopVideoView?) : Runnable {
        override fun run() {
            if (videoView != null && !videoView!!.isInPlayingState) {

                val videoOption =
                    SPUtils.getString(Constants.SP_HOME_OR_DETAIL_VIDEO_OPTION, Constants.VIDEO_OPTION_WIFI)
                        ?: Constants.VIDEO_OPTION_WIFI

                when (videoOption) {
                    Constants.VIDEO_OPTION_ALL -> {
                        startPlayLogic(videoView)
                    }

                    Constants.VIDEO_OPTION_WIFI -> {
                        if (NetworkUtils.isWifiConnected(HaloApp.getInstance().application)) {
                            startPlayLogic(videoView)
                        }
                    }

                    else -> {
                        //do nothing
                    }
                }
            }
        }
    }

    private fun startPlayLogic(videoView: TopVideoView?) {
        videoView?.startPlayLogic(true)
        currentPlayer = videoView
    }

}