package com.dynamicwallpaper.util;

import javax.imageio.ImageIO;
import java.awt.Dimension;
import java.io.File;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/** Sanity checks run before handing a batch of images to the native helper. */
public final class ImageValidation {

    private ImageValidation() {
    }

    /**
     * Dynamic wallpapers look best when every embedded image shares the same
     * pixel dimensions. This reads each file's size (without decoding full
     * pixel data) and returns a human-readable warning if they differ, or
     * {@code null} if everything matches or sizes couldn't be determined.
     */
    public static String checkConsistentDimensions(List<File> files) {
        Map<Dimension, Integer> counts = new LinkedHashMap<>();
        for (File file : files) {
            Dimension size = readSize(file);
            if (size == null) {
                continue;
            }
            counts.merge(size, 1, Integer::sum);
        }
        if (counts.size() <= 1) {
            return null;
        }
        StringBuilder sb = new StringBuilder("Your images have different dimensions:\n");
        for (Map.Entry<Dimension, Integer> entry : counts.entrySet()) {
            Dimension d = entry.getKey();
            sb.append(String.format("  %d x %d  (%d image%s)%n", d.width, d.height, entry.getValue(),
                    entry.getValue() == 1 ? "" : "s"));
        }
        sb.append("macOS will still accept the file, but for best results every image in a Dynamic ")
                .append("Desktop wallpaper should be the same size.");
        return sb.toString();
    }

    private static Dimension readSize(File file) {
        try {
            var readers = ImageIO.getImageReaders(ImageIO.createImageInputStream(file));
            if (!readers.hasNext()) {
                return null;
            }
            var reader = readers.next();
            try (var stream = ImageIO.createImageInputStream(file)) {
                reader.setInput(stream);
                return new Dimension(reader.getWidth(0), reader.getHeight(0));
            } finally {
                reader.dispose();
            }
        } catch (Exception e) {
            return null;
        }
    }
}
