package com.gensee.multi_instance.autoswipe

import android.util.Log
import androidx.viewpager2.widget.ViewPager2
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.cancel
import kotlinx.coroutines.delay
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch

/**
 *  author : guohaonan
 *  description : 自动滑动控制器，按固定间隔驱动 ViewPager2 翻页（ping-pong），
 *                用于压测快速滑动下列表视频的异常场景。与 SDK 和播放逻辑完全解耦，
 *                仅调用 ViewPager2.setCurrentItem。
 */
class AutoSwipeController(private val viewPager: ViewPager2) {

    companion object {
        private const val TAG = "AutoSwipeController"
    }

    private val scope = CoroutineScope(Dispatchers.Main + SupervisorJob())
    private var job: Job? = null
    private var direction = 1
    private var _running = false

    @Volatile
    var intervalMs: Long = 1000L

    val isRunning: Boolean
        get() = _running

    fun start() {
        if (_running) return
        if (pageCount() <= 1) {
            Log.i(TAG, "start: skipped, pageCount<=1")
            return
        }
        _running = true
        direction = 1
        job = scope.launch {
            while (isActive) {
                delay(intervalMs)
                swipeOnce()
            }
        }
    }

    fun stop() {
        _running = false
        job?.cancel()
        job = null
    }

    fun setInterval(ms: Long) {
        if (ms > 0) intervalMs = ms
    }

    private fun swipeOnce() {
        val count = pageCount()
        if (count <= 1) return
        var next = viewPager.currentItem + direction
        if (next >= count) {
            direction = -1
            next = count - 2
        } else if (next < 0) {
            direction = 1
            next = 1
        }
        next = next.coerceIn(0, count - 1)
        viewPager.setCurrentItem(next, true)
    }

    private fun pageCount(): Int = viewPager.adapter?.itemCount ?: 0

    fun destroy() {
        stop()
        scope.cancel()
    }
}
