package de.oaa.xxx.games.common.aufgaben;

import org.slf4j.LoggerFactory;

import javax.imageio.ImageIO;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

public class ImageScaler {

    private static final int MAX_SIZE = 128;

    public byte[] scale(byte[] origBytes) {
        try (ByteArrayInputStream bais = new ByteArrayInputStream(origBytes)) {
            BufferedImage orig = ImageIO.read(bais);
            if (orig == null) {
                return origBytes;
            }

            int origWidth  = orig.getWidth();
            int origHeight = orig.getHeight();

            // Bereits klein genug – unverändern zurückgeben
            if (origWidth <= MAX_SIZE && origHeight <= MAX_SIZE) {
                return origBytes;
            }

            // Seitenverhältnis beibehalten: längste Seite auf MAX_SIZE
            int newWidth, newHeight;
            if (origWidth >= origHeight) {
                newWidth  = MAX_SIZE;
                newHeight = Math.max(1, Math.round((float) MAX_SIZE * origHeight / origWidth));
            } else {
                newHeight = MAX_SIZE;
                newWidth  = Math.max(1, Math.round((float) MAX_SIZE * origWidth / origHeight));
            }

            BufferedImage scaled = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_ARGB);
            Graphics2D g = scaled.createGraphics();
            g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
            g.setRenderingHint(RenderingHints.KEY_RENDERING,     RenderingHints.VALUE_RENDER_QUALITY);
            g.drawImage(orig, 0, 0, newWidth, newHeight, null);
            g.dispose();

            try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
                ImageIO.write(scaled, "png", baos);
                return baos.toByteArray();
            }
        } catch (IOException e) {
            LoggerFactory.getLogger(ImageScaler.class).error("Fehler beim Skalieren des Bildes", e);
            return origBytes;
        }
    }
}
