001/*
002 * This file is part of Baritone.
003 *
004 * Baritone is free software: you can redistribute it and/or modify
005 * it under the terms of the GNU Lesser General Public License as published by
006 * the Free Software Foundation, either version 3 of the License, or
007 * (at your option) any later version.
008 *
009 * Baritone is distributed in the hope that it will be useful,
010 * but WITHOUT ANY WARRANTY; without even the implied warranty of
011 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
012 * GNU Lesser General Public License for more details.
013 *
014 * You should have received a copy of the GNU Lesser General Public License
015 * along with Baritone.  If not, see <https://www.gnu.org/licenses/>.
016 */
017
018package baritone.api.command.datatypes;
019
020import baritone.api.command.exception.CommandException;
021import baritone.api.command.helpers.TabCompleteHelper;
022import net.minecraft.entity.Entity;
023import net.minecraft.entity.EntityList;
024import net.minecraft.util.ResourceLocation;
025
026import java.util.stream.Stream;
027
028public enum EntityClassById implements IDatatypeFor<Class<? extends Entity>> {
029    INSTANCE;
030
031    @Override
032    public Class<? extends Entity> get(IDatatypeContext ctx) throws CommandException {
033        ResourceLocation id = new ResourceLocation(ctx.getConsumer().getString());
034        Class<? extends Entity> entity;
035        try {
036            entity = EntityList.REGISTRY.getObject(id);
037        } catch (NoSuchFieldError e) {
038            // Forge removes EntityList.REGISTRY field and provides the getClass method as a replacement
039            // See https://github.com/MinecraftForge/MinecraftForge/blob/1.12.x/patches/minecraft/net/minecraft/entity/EntityList.java.patch
040            try {
041                entity = (Class<? extends Entity>) EntityList.class.getMethod("getClass", ResourceLocation.class).invoke(null, id);
042            } catch (Exception ex) {
043                throw new RuntimeException("EntityList.REGISTRY does not exist and failed to call the Forge-replacement method", ex);
044            }
045        }
046
047        if (entity == null) {
048            throw new IllegalArgumentException("no entity found by that id");
049        }
050        return entity;
051    }
052
053    @Override
054    public Stream<String> tabComplete(IDatatypeContext ctx) throws CommandException {
055        return new TabCompleteHelper()
056                .append(EntityList.getEntityNameList().stream().map(Object::toString))
057                .filterPrefixNamespaced(ctx.getConsumer().getString())
058                .sortAlphabetically()
059                .stream();
060    }
061}