package eu.mhsl.minecraft.pixelpics.utils;

import org.bukkit.entity.Player;
import org.bukkit.map.MapCanvas;
import org.bukkit.map.MapRenderer;
import org.bukkit.map.MapView;
import org.jetbrains.annotations.NotNull;

import java.awt.image.BufferedImage;

public class ImageMapRenderer extends MapRenderer {
    public static final int MAP_SIZE = 128;
    private final BufferedImage image;
    private boolean alreadyRendered = false;

    public ImageMapRenderer(BufferedImage image) {
        this(image, 0, 0);
    }

    public ImageMapRenderer(BufferedImage image, int x, int y) {
        this.image = this.recalculateInput(image, x, y);
    }

    private BufferedImage recalculateInput(BufferedImage input, int x, int y) {
        if (x * MAP_SIZE > input.getWidth() || y * MAP_SIZE > input.getHeight())
            throw new RuntimeException(String.format("Input image mus match a multiple of x and y with %d", MAP_SIZE));

        int x1 = (int) (double) (x * MAP_SIZE);
        int y1 = (int) (double) (y * MAP_SIZE);

        int x2 = (int) (double) Math.min(input.getWidth(), ((x + 1) * MAP_SIZE));
        int y2 = (int) (double) Math.min(input.getHeight(), ((y + 1) * MAP_SIZE));

        if (x2 - x1 <= 0 || y2 - y1 <= 0)
            throw new RuntimeException("Invalid Image dimensions!");

        return input.getSubimage(x1, y1, x2 - x1, y2 - y1);
    }

    @Override
    public void render(@NotNull MapView map, @NotNull MapCanvas canvas, @NotNull Player player) {
        if(this.alreadyRendered) return;
        canvas.drawImage(0, 0, this.image);
        this.alreadyRendered = true;
    }
}
