package com.ardrawing.ardrawingspace.util;

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

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

public class DocumentManipulationTool {
    private static final boolean IS_DEBUG = false;

    public static float computeTouchDistance(MotionEvent event) {
        if (event == null || event.getPointerCount() < 2) return 0f;

        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 loadImageByPath(String path, ImageView imageView, Context context) {
        if (isInvalidInput(path, imageView, context)) return;

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

    private static boolean isInvalidInput(String path, ImageView imageView, Context context) {
        return path == null || imageView == null || context == null;
    }

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

    private static void loadTry(String path, ImageView imageView, Context context) {
        try (InputStream inputStream = context.getAssets().open(path)) {
            Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
            if (bitmap != null) {
                imageView.setImageBitmap(bitmap);
            } else {
                displayError(context, "Failed to decode asset image");
            }
        } catch (IOException e) {
            displayError(context, "Failed to load image from assets");
        }
    }

    private static Bitmap decodeBitmapFromFile(String path) {
        if (path.isEmpty()) return null;
        return BitmapFactory.decodeFile(path);
    }

    private static void displayError(Context context, String message) {
        if (context != null) {
            showToast(context, message);
        }
    }

    private static void showToast(Context context, String message) {
        if (IS_DEBUG) {
            Log.d("FileUtil", message);
        }
        Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
    }
}