package com.gh.gamecenter.home.custom

import android.os.Handler
import android.os.Looper
import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.LifecycleOwner
import androidx.recyclerview.widget.RecyclerView
import com.gh.gamecenter.gamecollection.square.GameCollectionSquareFragment

/**
 * 自定义页面
 * 控制折叠轮播图轮播逻辑
 */
class BannerInRecyclerController(
    private val nextPage: () -> Unit
) : DefaultLifecycleObserver {

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

    private var isAttachToWindow = false

    private var isActive = false

    private var isParentScrolling = false

    private var isDestroyed = false

    private val onScrollListener = object : RecyclerView.OnScrollListener() {
        override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
            isParentScrolling = newState != RecyclerView.SCROLL_STATE_IDLE
            if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                start()
            } else {
                pause()
            }
        }
    }

    fun onViewAttachedToWindow(parent: RecyclerView?) {
        isAttachToWindow = true
        parent?.addOnScrollListener(onScrollListener)
        start()
    }

    fun onViewDetachedFromWindow(parent: RecyclerView?) {
        isAttachToWindow = false
        pause()
        parent?.removeOnScrollListener(onScrollListener)
    }

    fun start() {
        if (isActive && !isParentScrolling && !isDestroyed) {
            handler.removeCallbacksAndMessages(null)
            nextToPage()
        }
    }

    fun pause() {
        handler.removeCallbacksAndMessages(null)
    }

    fun destroy() {
        handler.removeCallbacksAndMessages(null)
    }

    override fun onResume(owner: LifecycleOwner) {
        isActive = true
        if (isAttachToWindow) {
            start()
        }
    }

    override fun onPause(owner: LifecycleOwner) {
        isActive = false
        pause()
    }

    override fun onDestroy(owner: LifecycleOwner) {
        isDestroyed = true
        destroy()
    }

    private fun nextToPage() {
        handler.postDelayed(nextPageRunner, GameCollectionSquareFragment.BANNER_LOOP_TIME)
    }

    private val nextPageRunner = Runnable {
        nextPage()
        nextToPage()
    }
}