package eu.mhsl.minecraft.pixelblocks.listeners;

import eu.mhsl.minecraft.pixelblocks.PixelBlockItem;
import eu.mhsl.minecraft.pixelblocks.pixelblock.PixelBlock;
import eu.mhsl.minecraft.pixelblocks.pixelblock.PixelBlockWorld;
import eu.mhsl.minecraft.pixelblocks.utils.Direction;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.format.NamedTextColor;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockPlaceEvent;
import org.bukkit.inventory.ItemStack;

public class PlacePixelBlockListener implements Listener {
    @EventHandler(ignoreCancelled = true, priority = EventPriority.HIGH)
    public void onBlockPlace(BlockPlaceEvent event) {
        ItemStack usedItem = event.getItemInHand();
        PixelBlockItem.BlockInfo info = PixelBlockItem.getBlockInfo(usedItem);
        if(info == null) return;

        World playerWorld = event.getPlayer().getWorld();
        if(PixelBlockWorld.isPixelWorld(playerWorld)) {
            event.getPlayer().sendMessage(Component.translatable("pixelblocks.error.place-inside").color(NamedTextColor.RED));
            event.setCancelled(true);
            return;
        }

        if(PixelBlock.exists(info.id())) {
            event.getPlayer().sendMessage(Component.translatable("pixelblocks.error.already-exists").color(NamedTextColor.RED));
            event.setCancelled(true);
            return;
        }

        Location newBlockLocation = event.getBlock().getLocation();
        playerWorld.getBlockAt(newBlockLocation).setType(Material.AIR);

        Direction direction = Direction.vectorToDirection(event.getPlayer().getLocation().getDirection());

        PixelBlock.createPixelBlock(
            info.id(),
            info.hasOwner() ? info.owner() : event.getPlayer().getUniqueId(),
            newBlockLocation,
            direction
        );
    }
}
