package com.gh.common.view

import android.content.Context
import android.util.AttributeSet
import android.view.MotionEvent
import androidx.cardview.widget.CardView
import kotlin.math.abs

class InterceptVerticalScrollCardView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : CardView(context, attrs, defStyleAttr) {
    private var mOffsetX = 0F
    private var mOffsetY = 0F
    private var mLastPosX = 0F
    private var mLastPosY = 0F

    override fun dispatchTouchEvent(ev: MotionEvent): Boolean {
        return when (ev.action) {
            MotionEvent.ACTION_DOWN -> {
                mOffsetX = 0F
                mOffsetY = 0F
                mLastPosX = ev.x
                mLastPosY = ev.y
                super.dispatchTouchEvent(ev)
            }
            else -> {
                mOffsetX += abs(ev.x - mLastPosX)
                mOffsetY += abs(ev.y - mLastPosY)
                mLastPosX = ev.x
                mLastPosY = ev.y
                if (mOffsetX < mOffsetY) {
                    false
                } else {
                    super.dispatchTouchEvent(ev)
                }
            }
        }
    }
}