package com.ar.ardrawingboard.util;

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

public class TouchUtils {
    private static final int NONE = 0, DRAG = 1, ZOOM = 2;
    private static float initialDistance = 0f;
    private static final Matrix matrix = new Matrix();
    private static final Matrix savedMatrix = new Matrix();
    private static final PointF startPoint = new PointF();
    private static int mode = NONE;

    public static boolean handleTouchEvent(ImageView view, MotionEvent event) {
        switch (event.getActionMasked()) {
            case MotionEvent.ACTION_DOWN:
                savedMatrix.set(matrix);
                startPoint.set(event.getX(), event.getY());
                mode = DRAG;
                break;
            case MotionEvent.ACTION_POINTER_DOWN:
                initialDistance = Tracing.getDistance(event);
                if (initialDistance > 10f) {
                    savedMatrix.set(matrix);
                    mode = ZOOM;
                }
                break;
            case MotionEvent.ACTION_MOVE:
                if (mode == DRAG) {
                    matrix.set(savedMatrix);
                    matrix.postTranslate(event.getX() - startPoint.x, event.getY() - startPoint.y);
                } else if (mode == ZOOM) {
                    float newDist = Tracing.getDistance(event);
                    if (newDist > 10f) {
                        float scale = newDist / initialDistance;
                        matrix.set(savedMatrix);
                        matrix.postScale(scale, scale, view.getWidth() / 2f, view.getHeight() / 2f);
                    }
                }
                break;
            case MotionEvent.ACTION_UP:
            case MotionEvent.ACTION_POINTER_UP:
                mode = NONE;
                break;
        }
        view.setImageMatrix(matrix);
        return true;
    }

    public static void initPosition(ImageView imageView, Bitmap bitmap, Point screenSize) {
        float newX = screenSize.x / 2f - bitmap.getWidth() / 2f;
        float newY = screenSize.y / 2f - bitmap.getHeight() / 2f;
        matrix.postTranslate(newX, newY);
        imageView.setImageMatrix(matrix);
    }
}

