package com.gh.gamecenter.common.view

import android.content.Context
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.ViewConfiguration
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import kotlin.math.abs

class InterceptRecyclerView : RecyclerView {
    constructor(context: Context) : super(context)

    constructor(context: Context, attrs: AttributeSet) : super(context, attrs)

    constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr)

    private var startX = 0F
    private var startY = 0F

    override fun dispatchTouchEvent(ev: MotionEvent): Boolean {
        if (ev.action == MotionEvent.ACTION_DOWN) {
            startX = ev.x
            startY = ev.y
        } else if (ev.action == MotionEvent.ACTION_MOVE) {
            val dx = ev.x - startX
            val dy = ev.y - startY
            val scaledTouchSlop = ViewConfiguration.get(context).scaledTouchSlop
            if (layoutManager != null && layoutManager is LinearLayoutManager) {
                val orientation = (layoutManager as LinearLayoutManager).orientation
                if (orientation == HORIZONTAL) {
                    if (abs(dx) > scaledTouchSlop && abs(dx) > abs(dy)) {
                        parent.requestDisallowInterceptTouchEvent(true)
                    } else if (abs(dy) > scaledTouchSlop && abs(dy) > abs(dx)) {
                        parent.requestDisallowInterceptTouchEvent(false)
                    }
                }

            }
        }

        return super.dispatchTouchEvent(ev)
    }
}
