package com.mime.dualscreenview.view

import android.content.Context
import android.view.GestureDetector
import android.view.MotionEvent
import android.view.View


enum class TouchArea {
    Left,Center,Right
}

abstract class OnSwipeTouchListener(val context: Context?) : View.OnTouchListener {
    companion object {
        private const val SWIPE_DISTANCE_THRESHOLD = 100
        private const val SWIPE_VELOCITY_THRESHOLD = 100
    }
    private val gestureDetector: GestureDetector
    abstract fun onSwipeLeft()
    abstract fun onSwipeRight()
    abstract fun onSwipeDown()
    abstract fun onSwipeUp()
    abstract fun onSingleTap(area : TouchArea)

    override fun onTouch(v: View?, event: MotionEvent?): Boolean {
        if (event == null) {
            return false
        }
        return gestureDetector.onTouchEvent(event!!)
    }


    private inner class GestureListener : GestureDetector.SimpleOnGestureListener() {

        override fun onDown(e: MotionEvent): Boolean {
            return true
        }


        override fun onSingleTapUp(e: MotionEvent): Boolean {
            val width: Int = context?.resources?.displayMetrics?.widthPixels ?: 0
            val height: Int = context?.resources?.displayMetrics?.heightPixels ?: 0
            var touchArea : TouchArea = TouchArea.Center
            if(width > 0 && height > 0) {
                val centerAreaSize = width * 0.4
                var sideAreaSize = (width - centerAreaSize) * 0.5
                if(e.x < sideAreaSize) {
                    touchArea = TouchArea.Left
                } else if(e.x > sideAreaSize && e.x < width - sideAreaSize) {

                } else {
                    touchArea = TouchArea.Right
                }
            }
            onSingleTap(touchArea)
            return super.onSingleTapUp(e)
        }

        override fun onFling(
            e1: MotionEvent,
            e2: MotionEvent,
            velocityX: Float,
            velocityY: Float
        ): Boolean {

            val distanceX = e2.x - (e1?.x ?: 0f)
            val distanceY = e2.y - (e1?.y ?: 0f)
            if (Math.abs(distanceX) > Math.abs(distanceY)
                && Math.abs(distanceX) > SWIPE_DISTANCE_THRESHOLD
                && Math.abs(velocityX) > SWIPE_VELOCITY_THRESHOLD) {
                if (distanceX > 0) onSwipeRight() else onSwipeLeft()
                return true
            } else if (Math.abs(distanceY) > Math.abs(distanceX)
                && Math.abs(distanceY) > SWIPE_DISTANCE_THRESHOLD
                && Math.abs(velocityY) > SWIPE_VELOCITY_THRESHOLD) {
                if (distanceY > 0) onSwipeDown() else onSwipeUp()
                return true
            } else {

            }
            return false
        }
    }
    init {
        gestureDetector = GestureDetector(context, GestureListener())
    }
}