package eu.mhsl.minecraft.pixelpics.commands;

import eu.mhsl.minecraft.pixelpics.utils.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.bukkit.persistence.PersistentDataType;
import org.jetbrains.annotations.NotNull;

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

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!");

        if(args.length > 0)
            return false;

        // render image
        Resolution resolution = new Resolution(Resolution.Pixels._128P, Resolution.AspectRatio._1_1);
        BufferedImage image = Main.getInstance().getScreenRenderer().render(player.getEyeLocation(), resolution);

        // save image
        UUID imageId = UUID.randomUUID();
        File imageFolder = new File(Main.getInstance().getDataFolder(), "images");
        try {
            if(!imageFolder.exists() && !imageFolder.mkdirs())
                throw new IOException("Failed to create folders for image output!");

            ImageIO.write(image, "png", new File(imageFolder, String.format("%s.png", imageId)));
        } catch (IOException e) {
            throw new RuntimeException("Failed to save image to disk!");
        }

        // image item
        ItemStack map = new ItemStack(Material.FILLED_MAP, 1);
        MapMeta meta = (MapMeta) map.getItemMeta();
        meta.getPersistentDataContainer().set(Main.getInstance().pictureIdFlag, PersistentDataType.STRING, imageId.toString());

        // display image
        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);
        return true;
    }
}
