package com.gh.gamecenter.forum.home

import android.graphics.Rect
import android.os.Handler
import android.os.Looper
import android.text.TextUtils
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.common.utils.safelyGetInRelease
import com.gh.gamecenter.core.utils.MD5Utils
import com.gh.gamecenter.core.utils.SPUtils
import com.gh.gamecenter.entity.ForumVideoEntity
import com.gh.gamecenter.video.detail.CustomManager
import com.halo.assistant.HaloApp
import com.shuyu.gsyvideoplayer.video.base.GSYBaseVideoPlayer

class ForumScrollCalculatorHelper(
    private val horizontalId: Int,
    private val verticalId: Int,
    private val rangeTop: Int
) {
    private var firstVisible = -1
    private var lastVisible = 0
    private var visibleCount = 0
    private var runnable: PlayRunnable? = null
    var mItemData: List<ForumVideoEntity>? = null
    var currentPlayer: ArticleItemVideoView? = null
    var currentPosition = -1
    var mListRv: RecyclerView? = null

    private val playHandler = Handler(Looper.getMainLooper())

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

    fun onScroll(itemData: List<ForumVideoEntity>?, firstVisibleItem: Int, lastVisibleItem: Int) {
        mItemData = itemData
        firstVisible = firstVisibleItem
        lastVisible = lastVisibleItem
        visibleCount = lastVisibleItem - firstVisibleItem
        releaseIfNeeded()
    }

    fun reset() {
        firstVisible = -1
        lastVisible = 0
        visibleCount = 0
        if (runnable != null) {
            playHandler.removeCallbacks(runnable!!)
        }
        runnable = null
        mItemData = null
        if (currentPlayer != null) {
            CustomManager.releaseAllVideos(currentPlayer?.getKey())
        }
        currentPlayer = null
        currentPosition = -1
        mListRv = null
    }

    //判断player是否划出了屏幕，划出了屏幕则需要释放
    private fun releaseIfNeeded() {
        val rect = Rect()
        if (currentPlayer != null) {
            currentPlayer?.getLocalVisibleRect(rect)
            val height = currentPlayer?.height
            if (rect.top != 0 || rect.bottom != height) {
                //保存进度
                mItemData?.run {
                    if (currentPosition != -1 && currentPosition < size) {
                        val currentScheduler = currentPlayer?.currentPositionWhenPlaying?.toLong() ?: 0L
                        val video = mItemData?.safelyGetInRelease(currentPosition)
                        if (video != null) {
                            savePlaySchedule(MD5Utils.getContentMD5(video.url), 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: ArticleItemVideoView
        for (i in firstVisible until lastVisible + 1) {
            if (layoutManager == null || mItemData.isNullOrEmpty()) return

            val child = mListRv?.findViewHolderForAdapterPosition(i)?.itemView
            val horizontalPlayer: View? = child?.findViewById(horizontalId)
            val verticalPlayer: View? = child?.findViewById(verticalId)
            val player = when {
                horizontalPlayer?.visibility == View.VISIBLE -> horizontalPlayer
                verticalPlayer?.visibility == View.VISIBLE -> verticalPlayer
                else -> null
            }
            if (player == null || player !is ArticleItemVideoView) continue

            var video: ForumVideoEntity? = null
            mItemData?.run {
                if (i < size) {
                    video = mItemData?.safelyGetInRelease(i)
                }
            }
            if (video == null || TextUtils.isEmpty(video?.url) || video?.status == "pending" || video?.status == "fail") continue

            val rect = Rect()
            player.getLocalVisibleRect(rect)
            val height = player.height
            if (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 = PlayRunnable(gsyBaseVideoPlayer)
                    if (currentPlayer != null) {
                        CustomManager.releaseAllVideos(currentPlayer?.getKey())
//                        currentPlayer?.resetDetailMask()
                    }
                    currentPlayer = gsyBaseVideoPlayer
                    currentPosition = i
                    //降低频率
                    playHandler.postDelayed(runnable!!, 100)
                    break
                }
            }

        }
    }

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

                val videoOption =
                    SPUtils.getString(Constants.SP_CONTENT_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 -> {}
                }
            }
        }
    }

    private fun startPlayLogic(gsyBaseVideoPlayer: GSYBaseVideoPlayer?) {
        val videoView = gsyBaseVideoPlayer as? ArticleItemVideoView
//        val position = getPlaySchedule(MD5Utils.getContentMD5(topVideo.url))
//        if (position > 0) {
//            videoView?.seekOnStart = position
//        }
        videoView?.startPlayLogic()
    }

    companion object {

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

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

}