package com.ar.artraceartpro.utils;

import android.app.Activity;
import android.content.Context;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.Point;
import android.util.DisplayMetrics;
import android.view.MotionEvent;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.Toast;

import java.io.IOException;
import java.io.InputStream;

public class TracingUtils {

    public static float getDistance(MotionEvent event) {
        float dx = event.getX(1) - event.getX(0);
        float dy = event.getY(1) - event.getY(0);
        return (float) Math.sqrt(dx * dx + dy * dy);
    }

    public static void onInitIm(Context context, ImageView imageView, float imW, float imH) {
        Point screen = getScreen(context);

        float newX = screen.x / 2f - imW / 2;
        float newY = screen.y / 2f - imH / 2;

        Matrix matrix = new Matrix();
        matrix.postTranslate(newX, newY);

        imageView.setImageMatrix(matrix);
    }

    public static void displayImage(String imagePath, ImageView imageView, Context context, Bitmap bitmap, Activity activity) {
        if (imagePath.startsWith("/data/user/")) {
            displayImageFromStorage(imagePath,imageView,context);
        } else {
            displayImageFromAssets(imagePath,activity,context,bitmap,imageView);
        }

    }

    private static void displayImageFromStorage(String imagePath, ImageView imageView, Context context) {
        Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
        if (bitmap != null) {
            imageView.setImageBitmap(bitmap);
        } else {
            Toast.makeText(context, "Image loading failed", Toast.LENGTH_SHORT).show();
        }
    }

    private static void displayImageFromAssets(String imagePath, Activity activity, Context context, Bitmap bitmap, ImageView imageView) {
        try {
            AssetManager assetManager = activity.getAssets();
            InputStream inputStream = assetManager.open(imagePath);
            bitmap = BitmapFactory.decodeStream(inputStream);
            imageView.setImageBitmap(bitmap);
        } catch (IOException e) {
            e.printStackTrace();
            Toast.makeText(context, "Image loading failed: " + e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }

    private static Point getScreen(Context context) {
        DisplayMetrics displayMetrics = new DisplayMetrics();
        WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        if (windowManager != null) {
            windowManager.getDefaultDisplay().getMetrics(displayMetrics);
        }
        int width = displayMetrics.widthPixels;
        int height = displayMetrics.heightPixels;
        Point point = new Point();
        point.x = width;
        point.y = height;
        return point;
    }
}
