package com.adealink.weparty.commonui.recycleview

import android.content.Context
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.animation.LinearInterpolator
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.adealink.frame.base.fastLazy
import com.adealink.frame.util.DisplayUtil.dp2px
import java.lang.ref.WeakReference

class AutoRollRecycleView @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null, defStyle: Int = 0,
) : RecyclerView(context, attrs, defStyle) {

    companion object {
        private const val DEFAULT_ROLL_INTERVAL_MS = 1500L
        private const val DEFAULT_ROLL_DISTANCE_DP = 30F
    }

    var rollIntervalMs = DEFAULT_ROLL_INTERVAL_MS
    var rollDistancePx = dp2px(DEFAULT_ROLL_DISTANCE_DP)

    private var running = false
    private val autoRollTask by fastLazy { AutoRollTask(this, rollIntervalMs, rollDistancePx) }

    fun startRoll() {
        if (!running) {
            running = true
            postDelayed(autoRollTask, rollIntervalMs)
        }
    }

    fun stopRoll() {
        running = false
        removeCallbacks(autoRollTask)
    }

    class AutoRollTask(
        reference: AutoRollRecycleView,
        private val rollIntervalMs: Long,
        private val rollDistancePx: Int,
    ) : Runnable {

        private val reference by fastLazy { WeakReference<AutoRollRecycleView>(reference) }

        override fun run() {
            val recyclerView = reference.get() ?: return
            if (!recyclerView.running) {
                return
            }

            val layoutManager = recyclerView.layoutManager as? LinearLayoutManager
            val count = recyclerView.adapter?.itemCount ?: 0
            val position = layoutManager?.findLastVisibleItemPosition() ?: 0
            //防止错位滚动
            recyclerView.scrollToPosition(position)
            recyclerView.smoothScrollBy(0, rollDistancePx, LinearInterpolator())
            if (count == position + 1) {
                recyclerView.stopRoll()
            } else {
                recyclerView.postDelayed(recyclerView.autoRollTask, rollIntervalMs)
            }
        }
    }

    /**
     * 禁止手势滑动
     */
    override fun dispatchTouchEvent(ev: MotionEvent): Boolean {
        if (ev.action == MotionEvent.ACTION_MOVE) {
            return true
        }

        return super.dispatchTouchEvent(ev)
    }

}