package oppen.filters.ui.floating

/*

    Lätt - fast image filtering app for Android
    Copyright (C) 2020  Öppenlab

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <https://www.gnu.org/licenses/>.

 */

import android.annotation.SuppressLint
import android.view.MotionEvent
import android.view.View

@SuppressLint("ClickableViewAccessibility")
class FloatingTouchListener: View.OnTouchListener {

    private var deltaX = 0f
    private var deltaY = 0f

    override fun onTouch(view: View, event: MotionEvent): Boolean {
        when (event.action and MotionEvent.ACTION_MASK) {
            MotionEvent.ACTION_DOWN -> {
                deltaX = view.x - event.rawX
                deltaY = view.y - event.rawY
            }
            MotionEvent.ACTION_MOVE -> {
                //todo A comment on SO suggests using translationX/translationY here would be more performant as it's hardware backed
                //todo Possibly refactor this at this some point to use that instead
                view.animate()
                    .x(event.rawX + deltaX)
                    .y(event.rawY + deltaY)
                    .setDuration(0)
                    .start()
            }
            MotionEvent.ACTION_UP -> {
                view.x = event.rawX + deltaX
                view.y = event.rawY + deltaY
            }
        }

        return true
    }
}