package com.cherry.lib.doc.widget

import android.annotation.SuppressLint
import android.util.Log
import android.view.MotionEvent
import android.view.View
import kotlin.math.sqrt

const val TAP_THRESHOLD = 100
const val TAP_INTERVAL = 250

class MyOnTouchLister : View.OnTouchListener {
    private val TAG = "MyOnTouchLister"
    private var lastActionDownTime = 0L

    var singleTapAction: (() -> Unit)? = null
    private var lastX = 0f
    private var lastY = 0f

    @SuppressLint("ClickableViewAccessibility")
    override fun onTouch(v: View, event: MotionEvent): Boolean {
        Log.e(TAG, "onTouch")
        when (event.action) {
            MotionEvent.ACTION_DOWN -> {
                Log.e(TAG, "ACTION_DOWN")
                lastActionDownTime = System.currentTimeMillis()
                // 记录按下时的位置
                lastX = event.x
                lastY = event.y
            }

            MotionEvent.ACTION_UP -> {
                val flag1 = (System.currentTimeMillis() - lastActionDownTime) < TAP_INTERVAL
                val deltaX = event.x - lastX
                val deltaY = event.y - lastY
                val flag2 = moveSqrt(deltaX, deltaY) < TAP_THRESHOLD
                if (flag1 && flag2) {
                    Log.e(TAG, "ACTION_UP flag1=$flag1 flag2=$flag2")
                    singleTapAction?.invoke()
                }
            }
        }

        return false
    }

    private fun moveSqrt(deltaX: Float, deltaY: Float): Double {
        return sqrt((deltaX * deltaX + deltaY * deltaY).toDouble())
    }
}