package com.dynamicwallpaper.util;

import javax.imageio.ImageIO;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/** Loads small cached preview thumbnails for source images shown in the image tables. */
public final class ThumbnailLoader {

    private static final Map<String, ImageIcon> CACHE = new ConcurrentHashMap<>();

    private ThumbnailLoader() {
    }

    /** Returns a square thumbnail icon for the given file, or a neutral placeholder if it can't be read. */
    public static Icon thumbnail(File file, int size) {
        String key = file.getAbsolutePath() + "@" + size + "#" + file.lastModified();
        return CACHE.computeIfAbsent(key, k -> loadThumbnail(file, size));
    }

    private static ImageIcon loadThumbnail(File file, int size) {
        try {
            BufferedImage source = ImageIO.read(file);
            if (source == null) {
                return placeholder(size);
            }
            BufferedImage square = new BufferedImage(size, size, BufferedImage.TYPE_INT_ARGB);
            Graphics2D g = square.createGraphics();
            g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
            g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);

            double scale = Math.max((double) size / source.getWidth(), (double) size / source.getHeight());
            int drawWidth = (int) Math.ceil(source.getWidth() * scale);
            int drawHeight = (int) Math.ceil(source.getHeight() * scale);
            int x = (size - drawWidth) / 2;
            int y = (size - drawHeight) / 2;
            g.drawImage(source, x, y, drawWidth, drawHeight, null);
            g.dispose();
            return new ImageIcon(square);
        } catch (Exception e) {
            return placeholder(size);
        }
    }

    private static ImageIcon placeholder(int size) {
        BufferedImage image = new BufferedImage(size, size, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g = image.createGraphics();
        g.setColor(new Color(0, 0, 0, 40));
        g.fillRoundRect(0, 0, size, size, 8, 8);
        g.setColor(new Color(0, 0, 0, 100));
        g.drawRoundRect(0, 0, size - 1, size - 1, 8, 8);
        g.dispose();
        return new ImageIcon(image);
    }
}
