package eu.mhsl.minecraft.pixelblocks.pixelblock;

import eu.mhsl.minecraft.pixelblocks.Main;
import eu.mhsl.minecraft.pixelblocks.utils.EntityTagUtil;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.NamespacedKey;
import org.bukkit.World;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.ItemDisplay;
import org.bukkit.inventory.ItemStack;
import org.bukkit.util.Transformation;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

public class PixelBlockPlaceholder {
    private static final NamespacedKey placeholderOfTag = new NamespacedKey(Main.plugin(), "placeholder_of");

    private final PixelBlock parentBlock;

    public PixelBlockPlaceholder(PixelBlock parentBlock) {
        this.parentBlock = parentBlock;
    }

    public void spawn() {
        if(parentBlock.getPixelData().size() > 5) return;

        List<ItemDisplay> placeholders = new ArrayList<>();
        Location pixelBlockLocation = parentBlock.getPixelBlockLocation();
        UUID parentBlockUUID = parentBlock.getBlockUUID();

        World pixelBlockWorld = pixelBlockLocation.getWorld();
        Location itemDisplayLocation = pixelBlockLocation.add(0.5, 0.5, 0.5);

        for(int i = 0; i <= 90; i += 90) {
            ItemDisplay verticalCore = (ItemDisplay) pixelBlockWorld.spawnEntity(
                itemDisplayLocation,
                EntityType.ITEM_DISPLAY
            );
            verticalCore.setRotation(i, 0);
            placeholders.add(verticalCore);
        }

        ItemDisplay horizontalCore = (ItemDisplay) pixelBlockWorld.spawnEntity(
            itemDisplayLocation,
            EntityType.ITEM_DISPLAY
        );
        horizontalCore.setRotation(0, 90);
        placeholders.add(horizontalCore);

        placeholders.forEach(coreDisplay -> {
            coreDisplay.setItemStack(ItemStack.of(Material.END_CRYSTAL));
            Transformation transform = coreDisplay.getTransformation();
            transform.getScale().set(0.5);
            coreDisplay.setTransformation(transform);
        });

        ItemDisplay displayContainer = (ItemDisplay) pixelBlockWorld.spawnEntity(
            itemDisplayLocation,
            EntityType.ITEM_DISPLAY
        );
        displayContainer.setItemStack(ItemStack.of(Material.WHITE_STAINED_GLASS));
        placeholders.add(displayContainer);

        placeholders.forEach(placeholder -> EntityTagUtil.tag(placeholder, placeholderOfTag, parentBlockUUID));
    }

    public void destroy() {
        EntityTagUtil.removeTagged(this.parentBlock.getPixelBlockLocation(), ItemDisplay.class, placeholderOfTag, this.parentBlock.getBlockUUID());
    }
}
