package com.ardraw.ardrawinggallery.util;

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 ImageManager {
    public static float calculateDistanceBetweenTouches(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 void loadImage(String path, ImageView imageView, Context context, Activity activity) {
        if (path.startsWith("/data/user/")) {
            loadImageFromStorage(path, imageView, context);
        } else {
            loadImageFromAssets(path, activity, context, imageView);
        }
    }

    private static void loadImageFromStorage(String path, ImageView imageView, Context context) {
        Bitmap bitmap = BitmapFactory.decodeFile(path);
        if (bitmap != null) {
            imageView.setImageBitmap(bitmap);
        } else {
            showToast(context, "Failed to load image from storage");
        }
    }

    private static void loadImageFromAssets(String path, Activity activity, Context context, ImageView imageView) {
        try {
            AssetManager assetManager = activity.getAssets();
            InputStream inputStream = assetManager.open(path);
            Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
            imageView.setImageBitmap(bitmap);
        } catch (IOException e) {
            e.printStackTrace();
            showToast(context, "Failed to load image from assets: " + e.getMessage());
        }
    }

    private static Point getScreenSize(Context context) {
        DisplayMetrics metrics = new DisplayMetrics();
        WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        if (windowManager != null) {
            windowManager.getDefaultDisplay().getMetrics(metrics);
        }
        int width = metrics.widthPixels;
        int height = metrics.heightPixels;
        return new Point(width, height);
    }

    private static void showToast(Context context, String message) {
        Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
    }
}

