package eu.mhsl.minenet.minigames.command.privileged;

import eu.mhsl.minenet.minigames.command.PrivilegedCommand;
import eu.mhsl.minenet.minigames.instance.room.Room;
import eu.mhsl.minenet.minigames.message.Icon;
import eu.mhsl.minenet.minigames.message.type.ChatMessage;
import net.minestom.server.MinecraftServer;
import net.minestom.server.command.builder.arguments.ArgumentType;
import net.minestom.server.command.builder.condition.CommandCondition;
import net.minestom.server.entity.Player;

import java.util.Objects;

public class SetRoomOwnerCommand extends PrivilegedCommand {
    public SetRoomOwnerCommand() {
        super("setRoomOwner");

        addCondition((sender, commandString) -> ((Player) sender).getInstance() instanceof Room);

        setDefaultExecutor((sender, context) -> {
            if(sender instanceof Player p) {
                Room.getRoom(p).orElseThrow().setOwner(p);
                new ChatMessage(Icon.SUCCESS).appendStatic("You are now the owner of this room!").send(sender);
            }
        });

        addSyntax((sender, context) -> {
            System.out.println("Test");
            if(sender instanceof Player p) {
                Player newOwner = MinecraftServer.getConnectionManager().getOnlinePlayerByUsername(context.getRaw("player"));
                Room.getRoom(p).orElseThrow().setOwner(Objects.requireNonNull(newOwner));
                new ChatMessage(Icon.SUCCESS).appendStatic("The new owner has been set!").send(sender);
            }
        }, ArgumentType.Entity("player").onlyPlayers(true));
    }

    @Override
    protected CommandCondition isPrivileged() {
        return (sender, commandString) -> {
            Room playerRoom = Room.getRoom(((Player) sender)).orElse(null);
            return super.isPrivileged().canUse(sender, commandString) || (playerRoom != null && playerRoom.getOwner() == sender);
        };
    }
}
