package com.ardraw.ardrawinggallery.util;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.widget.Toast;

import com.ardraw.ardrawinggallery.room.ArData;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

public class ImageUtils {

    public static void saveImage(Uri imageUri, List<String> imagePaths, DatabaseUtil dbUtil, Context appContext, Activity activity) {
        try {
            InputStream imageInputStream = appContext.getContentResolver().openInputStream(imageUri);
            Bitmap imageBitmap = BitmapFactory.decodeStream(imageInputStream);

            if (imageBitmap == null) {
                showToast(appContext, "Unable to load image");
                return;
            }

            File storageDir = appContext.getFilesDir();
            File imageFile = new File(storageDir, generateUniqueImageName() + ".jpg");
            try (FileOutputStream imageOutputStream = new FileOutputStream(imageFile)) {
                imageBitmap.compress(Bitmap.CompressFormat.JPEG, 100, imageOutputStream);
            }
            imageInputStream.close();

            String savedImagePath = imageFile.getAbsolutePath();

            new Thread(() -> handleImageSaving(savedImagePath, imagePaths, dbUtil, appContext, activity, imageFile)).start();

        } catch (IOException e) {
            e.printStackTrace();
            showToast(appContext, "Failed to save picture: " + e.getMessage());
        }
    }

    private static void handleImageSaving(String savedImagePath, List<String> imagePaths, DatabaseUtil dbUtil, Context appContext, Activity activity, File imageFile) {
        if (isImageAlreadyPresent(savedImagePath, imagePaths, dbUtil)) {
            activity.runOnUiThread(() -> showToast(appContext, "The image already exists"));
            imageFile.delete();
            return;
        }

        imagePaths.add(savedImagePath);
        dbUtil.insert(new ArData(savedImagePath, true, false));
    }

    private static boolean isImageAlreadyPresent(String imagePath, List<String> imagePaths, DatabaseUtil dbUtil) {
        File newImageFile = new File(imagePath);

        for (String path : imagePaths) {
            File existingFile = new File(path);
            if (isFileSizeMatching(existingFile, newImageFile)) {
                return true;
            }
        }

        List<ArData> databaseImages = dbUtil.getAllImport();
        for (ArData arData : databaseImages) {
            File existingFile = new File(arData.getImagePath());
            if (isFileSizeMatching(existingFile, newImageFile)) {
                return true;
            }
        }

        return false;
    }

    private static boolean isFileSizeMatching(File file1, File file2) {
        return file1.length() == file2.length();
    }

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

    private static String generateUniqueImageName() {
        return String.valueOf(System.currentTimeMillis());
    }

    public static boolean isImageSizeValid(Uri imageUri, Context context) throws IOException {
        InputStream imageInputStream = context.getContentResolver().openInputStream(imageUri);
        if (imageInputStream == null) {
            return false;
        }

        long imageSize = imageInputStream.available();
        imageInputStream.close();
        long maxSize = 10 * 1024 * 1024;

        return imageSize <= maxSize;
    }
}

