package com.ardraw.ardrawingflow.util;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.MotionEvent;
import android.widget.ImageView;
import android.widget.Toast;

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

public class FileUtil {
    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) {
        if (path == null || imageView == null || context == null) return;

        if (path.startsWith("/data/user/")) {
            loadImageFromStorage(path, imageView, context);
        } else {
            loadImageFromAssets(path, imageView, context);
        }
    }

    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, ImageView imageView, Context context) {
        try (InputStream inputStream = context.getAssets().open(path)) {
            Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
            imageView.setImageBitmap(bitmap);
        } catch (IOException e) {
            showToast(context, "Failed to load image from assets");
        }
    }

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

