package eu.mhsl.minecraft.pixelpics.commands;

import eu.mhsl.minecraft.pixelpics.ImageMapRenderer;
import eu.mhsl.minecraft.pixelpics.Main;
import eu.mhsl.minecraft.pixelpics.render.render.Resolution;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.MapMeta;
import org.bukkit.map.MapView;
import org.jetbrains.annotations.NotNull;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;

public class PixelPicsCommand implements CommandExecutor {
    @Override
    public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, @NotNull String @NotNull [] args) {
        if(!(sender instanceof Player player))
            throw new IllegalStateException("Dieser Command kann nur von einem Spieler ausgeführt werden!");

        Resolution.Pixels pixels = Resolution.Pixels._128P;
        Resolution.AspectRatio aspectRatio = Resolution.AspectRatio._1_1;
        Resolution resolution = new Resolution(pixels, aspectRatio);

        BufferedImage image = Main.getInstance().getScreenRenderer().render(player, resolution);

        File file = new File(Main.getInstance().getDataFolder(), "Bild" + ".png");
        try {
            Main.getInstance().getDataFolder().mkdir();
            ImageIO.write(image, "png", file);
        } catch (Exception e) {
            return true;
        }

        ItemStack map = new ItemStack(Material.FILLED_MAP, 1);
        MapMeta meta = (MapMeta) map.getItemMeta();

        MapView mapView = Bukkit.createMap(Bukkit.getWorlds().getFirst());
        mapView.getRenderers().forEach(mapView::removeRenderer);
        mapView.addRenderer(new ImageMapRenderer(image));

        meta.setMapView(mapView);
        map.setItemMeta(meta);

        player.getInventory().addItem(map);
        player.updateInventory();

        return true;
    }
}
