package org.example.petshopdesktop.util;

import javafx.application.Platform;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import org.example.petshopdesktop.api.ApiClient;

import java.io.ByteArrayInputStream;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public final class DesktopImageSupport {

    private static final Map<String, Image> IMAGE_CACHE = new ConcurrentHashMap<>();

    private DesktopImageSupport() {
    }

    public static void loadImageInto(ImageView imageView, String imageUrl, double width, double height) {
        imageView.setFitWidth(width);
        imageView.setFitHeight(height);
        imageView.setPreserveRatio(true);
        imageView.setSmooth(true);
        imageView.setImage(null);

        if (imageUrl == null || imageUrl.isBlank()) {
            return;
        }

        if (imageUrl.startsWith("file:")) {
            Image image = new Image(imageUrl, 0, 0, true, true);
            if (!image.isError()) {
                imageView.setImage(image);
            }
            return;
        }

        Image cached = IMAGE_CACHE.get(imageUrl);
        if (cached != null) {
            imageView.setImage(cached);
            return;
        }

        new Thread(() -> {
            try {
                byte[] bytes = ApiClient.getInstance().getBytes(imageUrl);
                Image image = new Image(new ByteArrayInputStream(bytes));
                if (!image.isError()) {
                    IMAGE_CACHE.put(imageUrl, image);
                    Platform.runLater(() -> imageView.setImage(image));
                }
            } catch (Exception ignored) {
            }
        }, "desktop-image-loader").start();
    }

    public static void evict(String imageUrl) {
        if (imageUrl != null && !imageUrl.isBlank()) {
            IMAGE_CACHE.remove(imageUrl);
        }
    }
}
