001package co.aikar.commands;
002
003import com.velocitypowered.api.proxy.Player;
004import com.velocitypowered.api.proxy.ProxyServer;
005import net.kyori.adventure.text.TextComponent;
006import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer;
007import org.jetbrains.annotations.Nullable;
008
009import java.util.ArrayList;
010import java.util.Collection;
011import java.util.Collections;
012import java.util.List;
013import java.util.Optional;
014import java.util.stream.Collectors;
015
016public class ACFVelocityUtil {
017
018    public static TextComponent color(String message) {
019        return LegacyComponentSerializer.legacySection().deserialize(message);
020    }
021
022    public static Player findPlayerSmart(ProxyServer server, CommandIssuer issuer, String search) {
023        String name = ACFUtil.replace(search, ":confirm", "");
024
025        List<Player> matches = new ArrayList<>(matchPlayer(server, name));
026
027        if (matches.size() > 1) {
028            String allMatches = matches.stream().map(Player::getUsername).collect(Collectors.joining(", "));
029            issuer.sendError(MinecraftMessageKeys.MULTIPLE_PLAYERS_MATCH, "{search}", name, "{all}", allMatches);
030            return null;
031        }
032
033        if (matches.isEmpty()) {
034            if (!issuer.getManager().isValidName(name)) {
035                issuer.sendError(MinecraftMessageKeys.IS_NOT_A_VALID_NAME, "{name}", name);
036                return null;
037            }
038            issuer.sendError(MinecraftMessageKeys.NO_PLAYER_FOUND_SERVER, "{search}", name);
039            return null;
040        }
041
042        return matches.get(0);
043    }
044
045    /*
046     * Original code written by md_5
047     *
048     * Modified to work with Velocity by Crypnotic
049     */
050    private static Collection<Player> matchPlayer(ProxyServer server, final String partialName) {
051        // A better error message might be nice. This just mimics the previous output
052        if (partialName == null) {
053            throw new NullPointerException("partialName");
054        }
055
056        Optional<Player> exactMatch = server.getPlayer(partialName);
057        if (exactMatch.isPresent()) {
058            return Collections.singleton(exactMatch.get());
059        }
060
061        return server.getAllPlayers().stream()
062                .filter(player -> player.getUsername().regionMatches(true, 0, partialName, 0, partialName.length()))
063                .collect(Collectors.toList());
064    }
065
066    public static boolean isValidName(@Nullable String name) {
067        return name != null && !name.isEmpty() && ACFPatterns.VALID_NAME_PATTERN.matcher(name).matches();
068    }
069
070    public static <T> T validate(T object, String message, Object... values) {
071        if (object == null) {
072            throw new NullPointerException(String.format(message, values));
073        }
074        return object;
075    }
076}