package com.dlc.eboard.ui.widget

import android.content.Context
import android.util.AttributeSet
import android.view.MotionEvent
import androidx.recyclerview.widget.RecyclerView

/**
 * info
 *
 * @author ReiChin_
 */
class LooperRecyclerView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) :
    RecyclerView(context, attrs, defStyleAttr), Runnable {

    companion object {
        private const val TIME_AUTO_POLL = 16L
    }

    private var itemPageCount: Int = 0 // 一页的Item数
    private var itemAllCount: Int = 0
    private var scrollTime: Long = 1500

    private var running = false // 标示是否正在自动轮询

    fun initTimer(itemPageCount: Int, itemAllCount: Int) {
        this.itemPageCount = itemPageCount
        this.itemAllCount = itemAllCount
    }

    fun startAuto(scrollTime: Long) {
        this.scrollTime = scrollTime

        if (running) stopAuto()

        running = true
        postDelayed(this, scrollTime)
    }

    fun stopAuto() {
        running = false
        removeCallbacks(this)
    }

    override fun run() {
        if (itemPageCount < itemAllCount) {
            if (running) {
                scrollBy(2, 2)
                postDelayed(this, TIME_AUTO_POLL)
            }
        } else {
            postDelayed(this, scrollTime)
        }
    }

    override fun onTouchEvent(e: MotionEvent?): Boolean {
        when (e?.action) {
            MotionEvent.ACTION_DOWN -> if (running) stopAuto()
            MotionEvent.ACTION_UP,
            MotionEvent.ACTION_CANCEL,
            MotionEvent.ACTION_OUTSIDE -> startAuto(scrollTime)
        }
        return if (itemPageCount >= itemAllCount) true else super.onTouchEvent(e)
    }

}