package com.gh.gamecenter.home.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.video.detail.CustomManager
import com.halo.assistant.HaloApp
import com.shuyu.gsyvideoplayer.video.base.GSYBaseVideoPlayer

class ScrollCalculatorHelper(private val mListRv: RecyclerView, private val mPlayId: Int, private val mRangeTop: Int) {
    var currentPlayer: AutomaticVideoView? = null
    var currentPosition = -1
    private var mFirstVisible = -1
    private var mLastVisible = 0
    private var mRunnable: PlayRunnable? = null
    private val playHandler = Handler(Looper.getMainLooper())

    fun onScrollStateChanged(scrollState: Int) {
        if (scrollState == RecyclerView.SCROLL_STATE_IDLE) {
            playVideo(mListRv)
        }
    }

    fun onScroll(firstVisibleItem: Int, lastVisibleItem: Int) {
        mFirstVisible = firstVisibleItem
        mLastVisible = lastVisibleItem
        releaseIfNeeded()
    }

    //判断player是否划出了屏幕，划出了屏幕则需要释放
    private fun releaseIfNeeded() {
        val rect = Rect()
        if (currentPlayer != null) {
            currentPlayer?.getLocalVisibleRect(rect)
            val height = currentPlayer?.height
            if (rect.top != 0 || rect.bottom != height) {
                //保存进度
                val currentScheduler = currentPlayer?.currentPositionWhenPlaying?.toLong() ?: 0L
                savePlaySchedule(MD5Utils.getContentMD5(currentPlayer?.getUrl()), currentScheduler)
                CustomManager.releaseAllVideos(currentPlayer?.getKey())
                currentPlayer?.resetDetailMask()
                currentPlayer = null
                currentPosition = -1
            }
        }
    }

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

            val child = mListRv.findViewHolderForAdapterPosition(i)?.itemView
            val player: View? = child?.findViewById(mPlayId)
            if (player == null || player.visibility != View.VISIBLE || player !is AutomaticVideoView) continue

            val rect = Rect()
            player.getLocalVisibleRect(rect)
            val height = player.height
            if (rect.top == 0 && rect.bottom == height) {
                gsyBaseVideoPlayer = player
                if (mRunnable != null) {
                    playHandler.removeCallbacks(mRunnable!!)
                    mRunnable = null
                }
                if (currentPlayer == gsyBaseVideoPlayer) return
                val screenPosition = IntArray(2)
                gsyBaseVideoPlayer.getLocationInWindow(screenPosition)
                val rangePosition = screenPosition[1]
                if (rangePosition >= mRangeTop) {
                    mRunnable = PlayRunnable(gsyBaseVideoPlayer)
                    if (currentPlayer != null) {
                        CustomManager.releaseAllVideos(currentPlayer?.getKey())
                        currentPlayer?.resetDetailMask()
                    }
                    currentPlayer = gsyBaseVideoPlayer
                    currentPosition = i
                    //降低频率
                    playHandler.postDelayed(mRunnable!!, 100)
                    break
                }
            }

        }
    }

    private inner class PlayRunnable(var gsyBaseVideoPlayer: GSYBaseVideoPlayer?) : Runnable {
        override fun run() {
            if (gsyBaseVideoPlayer != null && !gsyBaseVideoPlayer!!.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(gsyBaseVideoPlayer)
                    }

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

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

    private fun startPlayLogic(gsyBaseVideoPlayer: GSYBaseVideoPlayer?) {
        val videoView = gsyBaseVideoPlayer as? AutomaticVideoView
        videoView?.startPlayLogic()
    }

    companion object {

        fun savePlaySchedule(key: String, schedule: Long) {
            val record = SPUtils.getMap(Constants.SP_HOME_VIDEO_PLAY_RECORD)
            record[key] = schedule.toString()
            SPUtils.setMap(Constants.SP_HOME_VIDEO_PLAY_RECORD, record)
        }

        fun getPlaySchedule(key: String): Long {
            val record = SPUtils.getMap(Constants.SP_HOME_VIDEO_PLAY_RECORD)
            return record[key]?.toLong() ?: 0L
        }
    }

}