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

import eu.mhsl.minenet.minigames.instance.hub.Hub;
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 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 final String prefix = "Suche: ";
    private String typedText = "";

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

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

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

    }

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

        this.typedText = this.formatInput(this.typedText);

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

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

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