package core.ui.widget

import android.content.Context
import android.view.MotionEvent
import android.view.View
import android.view.ViewConfiguration
import kotlin.math.abs
import kotlin.properties.Delegates

/**
 * info
 *
 * @author ReiChin_
 */
class SwipeTouchListener(
    context: Context,
    private val callback: (action: SwipeAction) -> Unit
) : View.OnTouchListener {

    private var mLastMotionX: Float = 0f
    private var mLastMotionY: Float = 0f

    private var mActivePointerId: Int = -1

    private var mTouchSlop by Delegates.notNull<Int>()

    init {
        mTouchSlop = ViewConfiguration.get(context).scaledPagingTouchSlop
    }

    override fun onTouch(v: View?, ev: MotionEvent?): Boolean {
        when (ev?.action?.and(MotionEvent.ACTION_MASK)) {
            MotionEvent.ACTION_DOWN -> {
                mLastMotionX = ev.x
                mLastMotionY = ev.y
                mActivePointerId = ev.getPointerId(0)
            }
            MotionEvent.ACTION_UP -> {
                val pointerIndex = ev.findPointerIndex(mActivePointerId)
                if (pointerIndex != -1) {
                    val x = ev.getX(pointerIndex)
                    val xDiff = abs(x - mLastMotionX)
                    val y = ev.getY(pointerIndex)
                    val yDiff = abs(y - mLastMotionY)
                    if (xDiff > mTouchSlop && xDiff > yDiff) {
                        val action = if (x > mLastMotionX) SwipeAction.PREV else SwipeAction.NEXT
                        callback.invoke(action)
                    }
                }
            }
        }

        return true
    }

}

enum class SwipeAction {
    PREV, NEXT
}