package com.ardraw.ardrawingflow.util;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Handler;
import android.os.Looper;
import android.widget.Toast;

import com.ardraw.ardrawingflow.data.database.entity.FlowData;
import com.ardraw.ardrawingflow.ui.viewmodel.FlowViewModel;

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

public class UploadUtil {
    private static final Handler mainHandler = new Handler(Looper.getMainLooper());

    public static void saveImage(Uri imageUri, List<String> imagePaths, FlowViewModel flowViewModel, Context context) {
        if (imageUri == null || imagePaths == null || flowViewModel == null || context == null)
            return;

        try (InputStream inputStream = context.getContentResolver().openInputStream(imageUri)) {
            Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
            if (bitmap == null) {
                showToast(context, "Unable to load image");
                return;
            }

            File imageFile = new File(context.getFilesDir(), generateUniqueImageName() + ".jpg");
            try (FileOutputStream outputStream = new FileOutputStream(imageFile)) {
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
            }

            String savedImagePath = imageFile.getAbsolutePath();
            new Thread(() -> handleImageSaving(savedImagePath, imagePaths, flowViewModel, context, imageFile)).start();
        } catch (IOException e) {
            showToast(context, "Failed to save picture");
        }
    }

    public static void deleteImage(FlowData flowData, FlowViewModel flowViewModel, Context context) {
        if (flowData.getImagePath() == null || flowViewModel == null || context == null) return;

        File imageFile = new File(flowData.getImagePath());
        if (!imageFile.exists()) {
            showToast(context, "Image does not exist");
            return;
        }

        if (imageFile.delete()) {
            flowViewModel.delete(flowData);
            showToast(context, "Image deleted successfully");
        } else {
            showToast(context, "Failed to delete image");
        }
    }

    private static void handleImageSaving(String savedImagePath, List<String> imagePaths, FlowViewModel flowViewModel, Context context, File imageFile) {
        if (isImageAlreadyPresent(savedImagePath, imagePaths, flowViewModel)) {
            imageFile.delete();
            showToast(context, "The image already exists");
            return;
        }

        imagePaths.add(savedImagePath);
        flowViewModel.insert(new FlowData(savedImagePath, true, false));
    }

    private static boolean isImageAlreadyPresent(String imagePath, List<String> imagePaths, FlowViewModel flowViewModel) {
        File newImageFile = new File(imagePath);
        if (!newImageFile.exists()) return false;

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

        List<FlowData> flowDataList = flowViewModel.getAdd();
        for (FlowData data : flowDataList) {
            File existingFile = new File(data.getImagePath());
            if (isFileSizeMatching(existingFile, newImageFile)) {
                return true;
            }
        }
        return false;
    }

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

    private static void showToast(Context context, String message) {
        if (context == null || message == null) return;
        mainHandler.post(() -> 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) {
        if (imageUri == null || context == null) return false;

        try (InputStream inputStream = context.getContentResolver().openInputStream(imageUri)) {
            if (inputStream == null) return false;
            long imageSize = inputStream.available();
            long maxSize = 10 * 1024 * 1024;
            return imageSize <= maxSize;
        } catch (IOException e) {
            return false;
        }
    }
}

