package com.ar.imagetracear.utils;

import android.graphics.Matrix;
import android.graphics.PointF;
import android.view.MotionEvent;
import android.widget.ImageView;

public class TouchEventHandler {

    private static final int TOUCH_NONE = 0;
    private static final int TOUCH_DRAG = 1;
    private static final int TOUCH_ZOOM = 2;

    private static float initialPointerDistance = 0f;
    private static final Matrix currentMatrix = new Matrix();
    private static final Matrix savedTransformMatrix = new Matrix();
    private static final PointF lastTouchPoint = new PointF();
    private static int currentTouchMode = TOUCH_NONE;

    public static boolean handleImageTouchEvent(ImageView view, MotionEvent event) {
        switch (event.getActionMasked()) {
            case MotionEvent.ACTION_DOWN:
                savedTransformMatrix.set(currentMatrix);
                lastTouchPoint.set(event.getX(), event.getY());
                currentTouchMode = TOUCH_DRAG;
                break;
            case MotionEvent.ACTION_POINTER_DOWN:
                initialPointerDistance = calculatePointerDistance(event);
                if (initialPointerDistance > 10f) {
                    savedTransformMatrix.set(currentMatrix);
                    currentTouchMode = TOUCH_ZOOM;
                }
                break;
            case MotionEvent.ACTION_MOVE:
                if (currentTouchMode == TOUCH_DRAG) {
                    currentMatrix.set(savedTransformMatrix);
                    currentMatrix.postTranslate(event.getX() - lastTouchPoint.x, event.getY() - lastTouchPoint.y);
                } else if (currentTouchMode == TOUCH_ZOOM) {
                    float newDistance = calculatePointerDistance(event);
                    if (newDistance > 10f) {
                        float scaleFactor = newDistance / initialPointerDistance;
                        currentMatrix.set(savedTransformMatrix);
                        currentMatrix.postScale(scaleFactor, scaleFactor, view.getWidth() / 2f, view.getHeight() / 2f);
                    }
                }
                break;
            case MotionEvent.ACTION_UP:
            case MotionEvent.ACTION_POINTER_UP:
                currentTouchMode = TOUCH_NONE;
                break;
        }
        view.setImageMatrix(currentMatrix);
        return true;
    }

    private static float calculatePointerDistance(MotionEvent event) {
        float deltaX = event.getX(1) - event.getX(0);
        float deltaY = event.getY(1) - event.getY(0);
        return (float) Math.sqrt(deltaX * deltaX + deltaY * deltaY);
    }

    public static Matrix getCurrentImageMatrix() {
        return currentMatrix;
    }

    public static void setInitialMatrix(Matrix matrix) {
        currentMatrix.set(matrix);
    }
}