package com.dspread.pos.utils;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Base64;
import android.util.Log;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

public class ImageUtils {
    private static final String TAG = "ImageUtils";

    /**
     * Saves the given Bitmap to a file in the application's internal storage.
     *
     * @param context  The application context.
     * @param bitmap   The Bitmap to save.
     * @param filename The desired filename (with extension).
     * @return The absolute path of the saved file.
     * @throws IOException If an error occurs while saving the file.
     */
    public static String saveBitmapToFile(Context context, Bitmap bitmap, String filename) throws IOException {
        File file = new File(context.getFilesDir(), filename);
        try (FileOutputStream fos = new FileOutputStream(file)) {
            // Compress and write the bitmap to the file
            if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos)) {
                Log.d(TAG, "Bitmap successfully saved as: " + filename);
            } else {
                Log.e(TAG, "Failed to compress the bitmap");
                throw new IOException("Failed to save bitmap.");
            }
            return file.getAbsolutePath();
        } catch (IOException e) {
            Log.e(TAG, "Error saving bitmap", e);
            throw e; // Rethrow to handle it at the calling function
        }
    }

    /**
     * Loads a Bitmap from a specified file path.
     *
     * @param filepath The path of the file to load the Bitmap from.
     * @return The loaded Bitmap, or null if an error occurs.
     */
    public static Bitmap loadBitmapFromFile(String filepath) {
        try {
            return BitmapFactory.decodeFile(filepath);
        } catch (Exception e) {
            Log.e(TAG, "Error loading bitmap from file: " + filepath, e);
            return null;
        }
    }

    /**
     * Decodes a Base64 encoded string into a Bitmap.
     *
     * @param input The Base64 encoded string which may include metadata.
     * @return The decoded Bitmap, or null if decoding fails.
     */
    public static Bitmap decodeFromBase64(String input) {
        try {
            // Handle base64 data that includes metadata (e.g., data:image/png;base64,)
            String base64Data = input.substring(input.indexOf(",") + 1);
            byte[] decodedBytes = Base64.decode(base64Data, Base64.DEFAULT);

            // Decode the byte array into a Bitmap
            return BitmapFactory.decodeByteArray(decodedBytes, 0, decodedBytes.length);
        } catch (Exception e) {
            Log.e(TAG, "Error decoding base64", e);
            return null;
        }
    }
}
