package se.urmo.game.util;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;

public class LoadSave {


    public static BufferedImage[][] loadSprites(final String fileName, final int rows, final int columns, int mapTilesize) {
        BufferedImage spriteSheet = LoadSave.GetSpriteAtlas(fileName);
        if(spriteSheet.getHeight() != rows * mapTilesize) throw new IllegalStateException("Wrong sprite row size");
        if(spriteSheet.getWidth() != columns * mapTilesize) throw new IllegalStateException("Wrong sprite colum size");
        BufferedImage[][] spriteBuffer = new BufferedImage[rows][columns];

        for (int row = 0; row < rows; row++) {
            for (int col = 0; col < columns; col++) {
                spriteBuffer[row][col] = spriteSheet.getSubimage(mapTilesize * col, mapTilesize * row, mapTilesize, mapTilesize);
            }
        }
        return spriteBuffer;
    }

    public static BufferedImage GetSpriteAtlas(String fileName) {
        BufferedImage img = null;
        InputStream is = LoadSave.class.getResourceAsStream("/" + fileName);
        try {
            img = ImageIO.read(is);

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return img;
    }

    public static BufferedImage rotate(BufferedImage img, double angleDegrees) {
        double angleRadians = Math.toRadians(angleDegrees);

        // Bildens dimensioner
        int w = img.getWidth();
        int h = img.getHeight();

        // Skapa en ny bild med samma storlek och stöd för transparens
        BufferedImage rotated = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g2d = rotated.createGraphics();

        // För bästa kvalitet
        g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
        g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

        // Skapa transform: rotera runt bildens mittpunkt
        AffineTransform transform = new AffineTransform();
        transform.rotate(angleRadians, w / 2.0, h / 2.0);

        // Rita originalbilden med transform
        g2d.setTransform(transform);
        g2d.drawImage(img, 0, 0, null);
        g2d.dispose();

        return rotated;
    }
}
