package eu.mhsl.minenet.minigames.instance.hub.inventory;

import eu.mhsl.minenet.minigames.instance.room.Room;
import eu.mhsl.minenet.minigames.message.Icon;
import eu.mhsl.minenet.minigames.message.component.TranslatedComponent;
import eu.mhsl.minenet.minigames.message.type.ChatMessage;
import eu.mhsl.minenet.minigames.shared.inventory.InteractableInventory;
import eu.mhsl.minenet.minigames.instance.hub.Hub;
import net.kyori.adventure.text.Component;
import net.minestom.server.MinecraftServer;
import net.minestom.server.entity.Player;
import net.minestom.server.event.player.PlayerPacketEvent;
import net.minestom.server.inventory.InventoryType;
import net.minestom.server.inventory.click.ClickType;
import net.minestom.server.inventory.condition.InventoryConditionResult;
import net.minestom.server.item.ItemStack;
import net.minestom.server.item.Material;
import net.minestom.server.network.packet.client.play.ClientNameItemPacket;

import java.util.Locale;
import java.util.Optional;

public class JoinInventory extends InteractableInventory {
    private String typedText = "";
    private final String prefix = "Suche: ";

    public JoinInventory(Player p) {
        super(InventoryType.ANVIL, TranslatedComponent.assemble("hub#join_title", p));

        setClickableItem(
                ItemStack.builder(Material.GREEN_STAINED_GLASS_PANE)
                        .customName(Component.text(prefix))
                        .build(),
                0,
                itemClick -> {}
        );

        Hub.INSTANCE.eventNode().addListener(PlayerPacketEvent.class, event -> {
            if (event.getPacket() instanceof ClientNameItemPacket packet) {
                typedText = packet.itemName();
            }
        });

    }

    @Override
    protected void onClick(Player player, int slot, ClickType clickType, InventoryConditionResult inventoryConditionResult) {
        if(slot != 2) return;
        inventoryConditionResult.setCancel(true);
        player.closeInventory();

        typedText = formatInput(typedText);

        Optional<Room> target = Room.getRoom(MinecraftServer.getConnectionManager().findOnlinePlayer(typedText));
        if(target.isPresent())
            Room.setRoom(player, target.get());
        else
            new ChatMessage(Icon.ERROR).appendTranslated("hub#join_notFound").appendStatic(" " + typedText).send(player);
    }

    private String formatInput(String raw) {
        if(raw.startsWith(prefix)) {
            raw = raw.split(prefix)[1];
        }

        return raw.toLowerCase(Locale.ROOT).trim();
    }
}
