package ru.dragonestia.kubik.msb.command;

import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.format.NamedTextColor;
import net.minestom.server.command.CommandSender;
import net.minestom.server.command.builder.Command;
import net.minestom.server.command.builder.CommandContext;
import net.minestom.server.command.builder.arguments.ArgumentString;
import net.minestom.server.command.builder.arguments.ArgumentType;
import net.minestom.server.entity.Player;
import ru.dragonestia.kubik.client.Kubik;
import ru.dragonestia.kubik.client.server.ServerControl;

public class TransferCommand extends Command {

    private final Kubik kubik;
    private final ServerControl serverControl;

    private final ArgumentString argServerId = ArgumentType.String("server_Id");
    private final ArgumentString argGroupId = ArgumentType.String("group_Id");

    public TransferCommand(Kubik kubik, ServerControl serverControl) {
        super("transfer");
        this.kubik = kubik;
        this.serverControl = serverControl;

        addSyntax(this::executeTransferCommandByServerId, ArgumentType.Literal("serverId"), argServerId);
        addSyntax(this::executeTransferCommandByGroupId, ArgumentType.Literal("groupId"), argGroupId);
    }

    private void executeTransferCommandByServerId(CommandSender sender, CommandContext ctx) {
        var player = (Player) sender;
        var serverId = ctx.get(argServerId);

        transfer(player, serverId);
    }

    private void executeTransferCommandByGroupId(CommandSender sender, CommandContext ctx) {
        var player = (Player) sender;
        var groupId = ctx.get(argGroupId);
        var serverId = kubik.pickServer(groupId);

        if (serverId == null) {
            player.sendMessage(Component.text("Cannot find server with groupId=%s".formatted(groupId), NamedTextColor.RED));
            return;
        }

        transfer(player, serverId);
    }

    private void transfer(Player player, String serverId) {
        player.sendMessage(Component.text("Trying transfer to %s".formatted(serverId), NamedTextColor.YELLOW));
        player.sendPluginMessage("kubik:transfer", serverId);
    }
}
