package com.auto.clicker.autoclicker.util;

import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;

public class DraggableHelper {

    public interface DragCallback {
        void onPositionChanged(int x, int y);
    }

    public static void makeDraggable(View view,
                                     WindowManager.LayoutParams params,
                                     WindowManager windowManager,
                                     int screenWidth, int screenHeight,
                                     DragCallback callback) {

        view.setOnTouchListener(new View.OnTouchListener() {
            private float lastX, lastY;
            private float paramX, paramY;

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        lastX = event.getRawX();
                        lastY = event.getRawY();
                        paramX = params.x;
                        paramY = params.y;
                        return true;

                    case MotionEvent.ACTION_MOVE:
                        float dx = event.getRawX() - lastX;
                        float dy = event.getRawY() - lastY;

                        int newX = (int) (paramX + dx);
                        int newY = (int) (paramY + dy);

                        newX = Math.max(0, Math.min(newX, screenWidth - view.getWidth()));
                        newY = Math.max(0, Math.min(newY, screenHeight - view.getHeight()));

                        params.x = newX;
                        params.y = newY;

                        windowManager.updateViewLayout(view, params);

                        if (callback != null) {
                            callback.onPositionChanged(newX, newY);
                        }
                        return true;

                    case MotionEvent.ACTION_UP:
                        v.performClick();
                        return true;
                }
                return false;
            }
        });
    }
}