package com.adealink.weparty.commonui.util

import android.view.MotionEvent
import android.view.View
import com.adealink.frame.base.fastLazy
import com.adealink.frame.util.DisplayUtil


class DragTouchListener(private val delay: Long = 0) :
    View.OnTouchListener {
    private var downX = 0f
    private var downY = 0f
    private var downTime: Long = 0
    private var isMove = false
    private var canDrag = false
    private fun haveDelay(): Boolean {
        return delay > 0
    }

    private val screenW by fastLazy { DisplayUtil.getScreenWidth() }

    private val screenH by fastLazy { DisplayUtil.getScreenHeight() }

    override fun onTouch(v: View, event: MotionEvent): Boolean {
        when (event.action) {
            MotionEvent.ACTION_DOWN -> {
                downX = event.x
                downY = event.y
                isMove = false
                downTime = System.currentTimeMillis()
                canDrag = !haveDelay()
            }

            MotionEvent.ACTION_MOVE -> {
                if (haveDelay() && !canDrag) {
                    val currMillis = System.currentTimeMillis()
                    if (currMillis - downTime >= delay) {
                        canDrag = true
                    }
                }
                if (!canDrag) {
                    return isMove
                }
                val xDistance = event.x - downX
                val yDistance = event.y - downY
                if (xDistance != 0f && yDistance != 0f) {
                    updateViewLayout(v, xDistance, yDistance)
                    isMove = true
                }
            }

            else -> {}
        }
        return isMove
    }

    private fun updateViewLayout(v: View, xDistance: Float, yDistance: Float) {
        var x = v.x + xDistance
        var y = v.y + yDistance
        x = 0f.coerceAtLeast(x)
        x = (screenW - v.width).toFloat().coerceAtMost(x)
        y = 0f.coerceAtLeast(y)
        y = (screenH - v.height).toFloat().coerceAtMost(y)
        v.x = x
        v.y = y
    }
}