package com.gh.gamecenter.common.view

import android.content.Context
import android.os.Build
import android.os.Handler
import android.os.Looper
import android.util.AttributeSet
import android.view.MotionEvent
import android.widget.LinearLayout
import androidx.annotation.Nullable
import androidx.core.view.children
import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.LifecycleOwner
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.RecyclerView.OnItemTouchListener
import java.lang.ref.WeakReference
import java.util.*

class CustomAutoScrollRecyclerViewContainerView(context: Context, @Nullable attrs: AttributeSet?) :
    LinearLayout(context, attrs), DefaultLifecycleObserver {

    private var isActive = false
    private var isAttached = false

    private val handler = Handler(Looper.getMainLooper())
    private val autoScrollTask = AutoScrollTask(this, handler)

    private var onItemTouchListener: OnItemTouchListener? = null

    private fun resumeScrolling() {
        handler.removeCallbacksAndMessages(null)
        handler.postDelayed(autoScrollTask, AUTO_SCROLL_INTERVAL)
    }


    private fun pauseScrolling() {
        handler.removeCallbacksAndMessages(null)
    }

    override fun onResume(owner: LifecycleOwner) {
        isActive = true
        if (isAttached) {
            resumeScrolling()
        }
    }

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

    private fun startAutoScroll() {
        if (isActive && isAttached) {
            resumeScrolling()
        }
    }

    override fun onAttachedToWindow() {
        super.onAttachedToWindow()
        if (onItemTouchListener == null) {
            onItemTouchListener = object : RecyclerView.OnItemTouchListener {
                override fun onTouchEvent(rv: RecyclerView, e: MotionEvent) {}
                override fun onInterceptTouchEvent(rv: RecyclerView, e: MotionEvent) =
                    rv.scrollState == RecyclerView.SCROLL_STATE_DRAGGING

                override fun onRequestDisallowInterceptTouchEvent(disallowIntercept: Boolean) {}
            }
        }
        children.forEach { child ->
            if (child is RecyclerView) {
                onItemTouchListener?.let {
                    child.removeOnItemTouchListener(it)
                    child.addOnItemTouchListener(it)
                }
            }
        }
        isAttached = true
        startAutoScroll()
    }

    override fun onDetachedFromWindow() {
        super.onDetachedFromWindow()
        isAttached = false
        pauseScrolling()
    }

    companion object {
        private const val AUTO_SCROLL_INTERVAL: Long = 10
    }

    class AutoScrollTask(
        reference: CustomAutoScrollRecyclerViewContainerView?,
        private val handler: Handler
    ) : Runnable {
        private val mReference: WeakReference<CustomAutoScrollRecyclerViewContainerView?>?
        private val mScrollSlop = if (Build.MODEL.toLowerCase(Locale.getDefault()) == "mumu") 1 else 2

        init {
            mReference = WeakReference(reference)
        }

        override fun run() {
            val containerView: CustomAutoScrollRecyclerViewContainerView? = mReference?.get()
            if (containerView != null) {
                for (child in containerView.children) {
                    if (child is RecyclerView) {
                        child.scrollBy(mScrollSlop, mScrollSlop)
                    }
                }
                handler.postDelayed(this, AUTO_SCROLL_INTERVAL)
            }
        }
    }
}
