package net.minecraft.commands.arguments;

import java.util.AbstractList;
import org.apache.commons.lang3.mutable.MutableBoolean;
import java.util.function.Consumer;
import net.minecraft.nbt.ListTag;
import net.minecraft.nbt.CollectionTag;
import java.util.Iterator;
import java.util.function.BiConsumer;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.Collections;
import java.util.Arrays;
import net.minecraft.network.chat.TranslatableComponent;
import com.mojang.brigadier.Message;
import net.minecraft.nbt.NbtUtils;
import net.minecraft.nbt.Tag;
import java.util.function.Predicate;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.nbt.TagParser;
import com.mojang.brigadier.ImmutableStringReader;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import it.unimi.dsi.fastutil.objects.Object2IntMap;
import java.util.List;
import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap;
import com.google.common.collect.Lists;
import com.mojang.brigadier.StringReader;
import net.minecraft.commands.CommandSourceStack;
import com.mojang.brigadier.context.CommandContext;
import com.mojang.brigadier.exceptions.DynamicCommandExceptionType;
import com.mojang.brigadier.exceptions.SimpleCommandExceptionType;
import java.util.Collection;
import com.mojang.brigadier.arguments.ArgumentType;

public class NbtPathArgument implements ArgumentType<NbtPath> {
    private static final Collection<String> EXAMPLES;
    public static final SimpleCommandExceptionType ERROR_INVALID_NODE;
    public static final DynamicCommandExceptionType ERROR_NOTHING_FOUND;
    
    public static NbtPathArgument nbtPath() {
        return new NbtPathArgument();
    }
    
    public static NbtPath getPath(final CommandContext<CommandSourceStack> commandContext, final String string) {
        return (NbtPath)commandContext.getArgument(string, (Class)NbtPath.class);
    }
    
    public NbtPath parse(final StringReader stringReader) throws CommandSyntaxException {
        final List<Node> list3 = Lists.newArrayList();
        final int integer4 = stringReader.getCursor();
        final Object2IntMap<Node> object2IntMap5 = (Object2IntMap<Node>)new Object2IntOpenHashMap();
        boolean boolean6 = true;
        while (stringReader.canRead() && stringReader.peek() != ' ') {
            final Node i7 = parseNode(stringReader, boolean6);
            list3.add(i7);
            object2IntMap5.put(i7, stringReader.getCursor() - integer4);
            boolean6 = false;
            if (stringReader.canRead()) {
                final char character8 = stringReader.peek();
                if (character8 == ' ' || character8 == '[' || character8 == '{') {
                    continue;
                }
                stringReader.expect('.');
            }
        }
        return new NbtPath(stringReader.getString().substring(integer4, stringReader.getCursor()), list3.<Node>toArray(new Node[0]), object2IntMap5);
    }
    
    private static Node parseNode(final StringReader stringReader, final boolean boolean2) throws CommandSyntaxException {
        switch (stringReader.peek()) {
            case '{': {
                if (!boolean2) {
                    throw NbtPathArgument.ERROR_INVALID_NODE.createWithContext((ImmutableStringReader)stringReader);
                }
                final CompoundTag jt3 = new TagParser(stringReader).readStruct();
                return new MatchRootObjectNode(jt3);
            }
            case '[': {
                stringReader.skip();
                final int integer3 = stringReader.peek();
                if (integer3 == 123) {
                    final CompoundTag jt4 = new TagParser(stringReader).readStruct();
                    stringReader.expect(']');
                    return new MatchElementNode(jt4);
                }
                if (integer3 == 93) {
                    stringReader.skip();
                    return AllElementsNode.INSTANCE;
                }
                final int integer4 = stringReader.readInt();
                stringReader.expect(']');
                return new IndexedElementNode(integer4);
            }
            case '\"': {
                final String string3 = stringReader.readString();
                return readObjectNode(stringReader, string3);
            }
            default: {
                final String string3 = readUnquotedName(stringReader);
                return readObjectNode(stringReader, string3);
            }
        }
    }
    
    private static Node readObjectNode(final StringReader stringReader, final String string) throws CommandSyntaxException {
        if (stringReader.canRead() && stringReader.peek() == '{') {
            final CompoundTag jt3 = new TagParser(stringReader).readStruct();
            return new MatchObjectNode(string, jt3);
        }
        return new CompoundChildNode(string);
    }
    
    private static String readUnquotedName(final StringReader stringReader) throws CommandSyntaxException {
        final int integer2 = stringReader.getCursor();
        while (stringReader.canRead() && isAllowedInUnquotedName(stringReader.peek())) {
            stringReader.skip();
        }
        if (stringReader.getCursor() == integer2) {
            throw NbtPathArgument.ERROR_INVALID_NODE.createWithContext((ImmutableStringReader)stringReader);
        }
        return stringReader.getString().substring(integer2, stringReader.getCursor());
    }
    
    public Collection<String> getExamples() {
        return NbtPathArgument.EXAMPLES;
    }
    
    private static boolean isAllowedInUnquotedName(final char character) {
        return character != ' ' && character != '\"' && character != '[' && character != ']' && character != '.' && character != '{' && character != '}';
    }
    
    private static Predicate<Tag> createTagPredicate(final CompoundTag jt) {
        return kj -> NbtUtils.compareNbt(jt, kj, true);
    }
    
    static {
        EXAMPLES = Arrays.<String>asList("foo", "foo.bar", "foo[0]", "[0]", "[]", "{foo=bar}");
        ERROR_INVALID_NODE = new SimpleCommandExceptionType((Message)new TranslatableComponent("arguments.nbtpath.node.invalid", new Object[0]));
        final TranslatableComponent translatableComponent;
        ERROR_NOTHING_FOUND = new DynamicCommandExceptionType(object -> {
            new TranslatableComponent("arguments.nbtpath.nothing_found", new Object[] { object });
            return translatableComponent;
        });
    }
    
    public static class NbtPath {
        private final String original;
        private final Object2IntMap<Node> nodeToOriginalPosition;
        private final Node[] nodes;
        
        public NbtPath(final String string, final Node[] arr, final Object2IntMap<Node> object2IntMap) {
            this.original = string;
            this.nodes = arr;
            this.nodeToOriginalPosition = object2IntMap;
        }
        
        public List<Tag> get(final Tag kj) throws CommandSyntaxException {
            List<Tag> list3 = Collections.<Tag>singletonList(kj);
            for (final Node i7 : this.nodes) {
                list3 = i7.get(list3);
                if (list3.isEmpty()) {
                    throw this.createNotFoundException(i7);
                }
            }
            return list3;
        }
        
        public int countMatching(final Tag kj) {
            List<Tag> list3 = Collections.<Tag>singletonList(kj);
            for (final Node i7 : this.nodes) {
                list3 = i7.get(list3);
                if (list3.isEmpty()) {
                    return 0;
                }
            }
            return list3.size();
        }
        
        private List<Tag> getOrCreateParents(final Tag kj) throws CommandSyntaxException {
            List<Tag> list3 = Collections.<Tag>singletonList(kj);
            for (int integer4 = 0; integer4 < this.nodes.length - 1; ++integer4) {
                final Node i5 = this.nodes[integer4];
                final int integer5 = integer4 + 1;
                list3 = i5.getOrCreate(list3, this.nodes[integer5]::createPreferredParentTag);
                if (list3.isEmpty()) {
                    throw this.createNotFoundException(i5);
                }
            }
            return list3;
        }
        
        public List<Tag> getOrCreate(final Tag kj, final Supplier<Tag> supplier) throws CommandSyntaxException {
            final List<Tag> list4 = this.getOrCreateParents(kj);
            final Node i5 = this.nodes[this.nodes.length - 1];
            return i5.getOrCreate(list4, supplier);
        }
        
        private static int apply(final List<Tag> list, final Function<Tag, Integer> function) {
            return list.stream().<Integer>map(function).reduce(Integer.valueOf(0), (integer1, integer2) -> integer1 + integer2);
        }
        
        public int set(final Tag kj, final Supplier<Tag> supplier) throws CommandSyntaxException {
            final List<Tag> list4 = this.getOrCreateParents(kj);
            final Node i5 = this.nodes[this.nodes.length - 1];
            return apply(list4, kj -> i5.setTag(kj, supplier));
        }
        
        public int remove(final Tag kj) {
            List<Tag> list3 = Collections.<Tag>singletonList(kj);
            for (int integer4 = 0; integer4 < this.nodes.length - 1; ++integer4) {
                list3 = this.nodes[integer4].get(list3);
            }
            final Node i4 = this.nodes[this.nodes.length - 1];
            return apply(list3, i4::removeTag);
        }
        
        private CommandSyntaxException createNotFoundException(final Node i) {
            final int integer3 = this.nodeToOriginalPosition.getInt(i);
            return NbtPathArgument.ERROR_NOTHING_FOUND.create(this.original.substring(0, integer3));
        }
        
        @Override
        public String toString() {
            return this.original;
        }
    }
    
    interface Node {
        void getTag(final Tag kj, final List<Tag> list);
        
        void getOrCreateTag(final Tag kj, final Supplier<Tag> supplier, final List<Tag> list);
        
        Tag createPreferredParentTag();
        
        int setTag(final Tag kj, final Supplier<Tag> supplier);
        
        int removeTag(final Tag kj);
        
        default List<Tag> get(final List<Tag> list) {
            return this.collect(list, this::getTag);
        }
        
        default List<Tag> getOrCreate(final List<Tag> list, final Supplier<Tag> supplier) {
            return this.collect(list, (kj, list) -> this.getOrCreateTag(kj, supplier, list));
        }
        
        default List<Tag> collect(final List<Tag> list, final BiConsumer<Tag, List<Tag>> biConsumer) {
            final List<Tag> list2 = Lists.newArrayList();
            for (final Tag kj6 : list) {
                biConsumer.accept(kj6, list2);
            }
            return list2;
        }
    }
    
    static class CompoundChildNode implements Node {
        private final String name;
        
        public CompoundChildNode(final String string) {
            this.name = string;
        }
        
        @Override
        public void getTag(final Tag kj, final List<Tag> list) {
            if (kj instanceof CompoundTag) {
                final Tag kj2 = ((CompoundTag)kj).get(this.name);
                if (kj2 != null) {
                    list.add(kj2);
                }
            }
        }
        
        @Override
        public void getOrCreateTag(final Tag kj, final Supplier<Tag> supplier, final List<Tag> list) {
            if (kj instanceof CompoundTag) {
                final CompoundTag jt5 = (CompoundTag)kj;
                Tag kj2;
                if (jt5.contains(this.name)) {
                    kj2 = jt5.get(this.name);
                }
                else {
                    kj2 = supplier.get();
                    jt5.put(this.name, kj2);
                }
                list.add(kj2);
            }
        }
        
        @Override
        public Tag createPreferredParentTag() {
            return new CompoundTag();
        }
        
        @Override
        public int setTag(final Tag kj, final Supplier<Tag> supplier) {
            if (kj instanceof CompoundTag) {
                final CompoundTag jt4 = (CompoundTag)kj;
                final Tag kj2 = supplier.get();
                final Tag kj3 = jt4.put(this.name, kj2);
                if (!kj2.equals(kj3)) {
                    return 1;
                }
            }
            return 0;
        }
        
        @Override
        public int removeTag(final Tag kj) {
            if (kj instanceof CompoundTag) {
                final CompoundTag jt3 = (CompoundTag)kj;
                if (jt3.contains(this.name)) {
                    jt3.remove(this.name);
                    return 1;
                }
            }
            return 0;
        }
    }
    
    static class IndexedElementNode implements Node {
        private final int index;
        
        public IndexedElementNode(final int integer) {
            this.index = integer;
        }
        
        @Override
        public void getTag(final Tag kj, final List<Tag> list) {
            if (kj instanceof CollectionTag) {
                final CollectionTag<?> js4 = kj;
                final int integer5 = js4.size();
                final int integer6 = (this.index < 0) ? (integer5 + this.index) : this.index;
                if (0 <= integer6 && integer6 < integer5) {
                    list.add(js4.get(integer6));
                }
            }
        }
        
        @Override
        public void getOrCreateTag(final Tag kj, final Supplier<Tag> supplier, final List<Tag> list) {
            this.getTag(kj, list);
        }
        
        @Override
        public Tag createPreferredParentTag() {
            return new ListTag();
        }
        
        @Override
        public int setTag(final Tag kj, final Supplier<Tag> supplier) {
            if (kj instanceof CollectionTag) {
                final CollectionTag<?> js4 = kj;
                final int integer5 = js4.size();
                final int integer6 = (this.index < 0) ? (integer5 + this.index) : this.index;
                if (0 <= integer6 && integer6 < integer5) {
                    final Tag kj2 = js4.get(integer6);
                    final Tag kj3 = supplier.get();
                    if (!kj3.equals(kj2) && js4.setTag(integer6, kj3)) {
                        return 1;
                    }
                }
            }
            return 0;
        }
        
        @Override
        public int removeTag(final Tag kj) {
            if (kj instanceof CollectionTag) {
                final CollectionTag<?> js3 = kj;
                final int integer4 = js3.size();
                final int integer5 = (this.index < 0) ? (integer4 + this.index) : this.index;
                if (0 <= integer5 && integer5 < integer4) {
                    js3.remove(integer5);
                    return 1;
                }
            }
            return 0;
        }
    }
    
    static class MatchElementNode implements Node {
        private final CompoundTag pattern;
        private final Predicate<Tag> predicate;
        
        public MatchElementNode(final CompoundTag jt) {
            this.pattern = jt;
            this.predicate = createTagPredicate(jt);
        }
        
        @Override
        public void getTag(final Tag kj, final List<Tag> list) {
            if (kj instanceof ListTag) {
                final ListTag jz4 = (ListTag)kj;
                jz4.stream().filter(this.predicate).forEach(list::add);
            }
        }
        
        @Override
        public void getOrCreateTag(final Tag kj, final Supplier<Tag> supplier, final List<Tag> list) {
            final MutableBoolean mutableBoolean5 = new MutableBoolean();
            if (kj instanceof ListTag) {
                final ListTag jz6 = (ListTag)kj;
                final MutableBoolean mutableBoolean6;
                jz6.stream().filter(this.predicate).forEach(kj -> {
                    list.add(kj);
                    mutableBoolean6.setTrue();
                    return;
                });
                if (mutableBoolean5.isFalse()) {
                    final CompoundTag jt7 = this.pattern.copy();
                    ((AbstractList<CompoundTag>)jz6).add(jt7);
                    list.add(jt7);
                }
            }
        }
        
        @Override
        public Tag createPreferredParentTag() {
            return new ListTag();
        }
        
        @Override
        public int setTag(final Tag kj, final Supplier<Tag> supplier) {
            int integer4 = 0;
            if (kj instanceof ListTag) {
                final ListTag jz5 = (ListTag)kj;
                final int integer5 = jz5.size();
                if (integer5 == 0) {
                    jz5.add(supplier.get());
                    ++integer4;
                }
                else {
                    for (int integer6 = 0; integer6 < integer5; ++integer6) {
                        final Tag kj2 = jz5.get(integer6);
                        if (this.predicate.test(kj2)) {
                            final Tag kj3 = supplier.get();
                            if (!kj3.equals(kj2) && jz5.setTag(integer6, kj3)) {
                                ++integer4;
                            }
                        }
                    }
                }
            }
            return integer4;
        }
        
        @Override
        public int removeTag(final Tag kj) {
            int integer3 = 0;
            if (kj instanceof ListTag) {
                final ListTag jz4 = (ListTag)kj;
                for (int integer4 = jz4.size() - 1; integer4 >= 0; --integer4) {
                    if (this.predicate.test(jz4.get(integer4))) {
                        jz4.remove(integer4);
                        ++integer3;
                    }
                }
            }
            return integer3;
        }
    }
    
    static class AllElementsNode implements Node {
        public static final AllElementsNode INSTANCE;
        
        private AllElementsNode() {
        }
        
        @Override
        public void getTag(final Tag kj, final List<Tag> list) {
            if (kj instanceof CollectionTag) {
                list.addAll(kj);
            }
        }
        
        @Override
        public void getOrCreateTag(final Tag kj, final Supplier<Tag> supplier, final List<Tag> list) {
            if (kj instanceof CollectionTag) {
                final CollectionTag<?> js5 = kj;
                if (js5.isEmpty()) {
                    final Tag kj2 = supplier.get();
                    if (js5.addTag(0, kj2)) {
                        list.add(kj2);
                    }
                }
                else {
                    list.addAll(js5);
                }
            }
        }
        
        @Override
        public Tag createPreferredParentTag() {
            return new ListTag();
        }
        
        @Override
        public int setTag(final Tag kj, final Supplier<Tag> supplier) {
            if (!(kj instanceof CollectionTag)) {
                return 0;
            }
            final CollectionTag<?> js4 = kj;
            final int integer5 = js4.size();
            if (integer5 == 0) {
                js4.addTag(0, supplier.get());
                return 1;
            }
            final Tag kj2 = supplier.get();
            final int integer6 = integer5 - (int)js4.stream().filter(kj2::equals).count();
            if (integer6 == 0) {
                return 0;
            }
            js4.clear();
            if (!js4.addTag(0, kj2)) {
                return 0;
            }
            for (int integer7 = 1; integer7 < integer5; ++integer7) {
                js4.addTag(integer7, supplier.get());
            }
            return integer6;
        }
        
        @Override
        public int removeTag(final Tag kj) {
            if (kj instanceof CollectionTag) {
                final CollectionTag<?> js3 = kj;
                final int integer4 = js3.size();
                if (integer4 > 0) {
                    js3.clear();
                    return integer4;
                }
            }
            return 0;
        }
        
        static {
            INSTANCE = new AllElementsNode();
        }
    }
    
    static class MatchObjectNode implements Node {
        private final String name;
        private final CompoundTag pattern;
        private final Predicate<Tag> predicate;
        
        public MatchObjectNode(final String string, final CompoundTag jt) {
            this.name = string;
            this.pattern = jt;
            this.predicate = createTagPredicate(jt);
        }
        
        @Override
        public void getTag(final Tag kj, final List<Tag> list) {
            if (kj instanceof CompoundTag) {
                final Tag kj2 = ((CompoundTag)kj).get(this.name);
                if (this.predicate.test(kj2)) {
                    list.add(kj2);
                }
            }
        }
        
        @Override
        public void getOrCreateTag(final Tag kj, final Supplier<Tag> supplier, final List<Tag> list) {
            if (kj instanceof CompoundTag) {
                final CompoundTag jt5 = (CompoundTag)kj;
                Tag kj2 = jt5.get(this.name);
                if (kj2 == null) {
                    kj2 = this.pattern.copy();
                    jt5.put(this.name, kj2);
                    list.add(kj2);
                }
                else if (this.predicate.test(kj2)) {
                    list.add(kj2);
                }
            }
        }
        
        @Override
        public Tag createPreferredParentTag() {
            return new CompoundTag();
        }
        
        @Override
        public int setTag(final Tag kj, final Supplier<Tag> supplier) {
            if (kj instanceof CompoundTag) {
                final CompoundTag jt4 = (CompoundTag)kj;
                final Tag kj2 = jt4.get(this.name);
                if (this.predicate.test(kj2)) {
                    final Tag kj3 = supplier.get();
                    if (!kj3.equals(kj2)) {
                        jt4.put(this.name, kj3);
                        return 1;
                    }
                }
            }
            return 0;
        }
        
        @Override
        public int removeTag(final Tag kj) {
            if (kj instanceof CompoundTag) {
                final CompoundTag jt3 = (CompoundTag)kj;
                final Tag kj2 = jt3.get(this.name);
                if (this.predicate.test(kj2)) {
                    jt3.remove(this.name);
                    return 1;
                }
            }
            return 0;
        }
    }
    
    static class MatchRootObjectNode implements Node {
        private final Predicate<Tag> predicate;
        
        public MatchRootObjectNode(final CompoundTag jt) {
            this.predicate = createTagPredicate(jt);
        }
        
        @Override
        public void getTag(final Tag kj, final List<Tag> list) {
            if (kj instanceof CompoundTag && this.predicate.test(kj)) {
                list.add(kj);
            }
        }
        
        @Override
        public void getOrCreateTag(final Tag kj, final Supplier<Tag> supplier, final List<Tag> list) {
            this.getTag(kj, list);
        }
        
        @Override
        public Tag createPreferredParentTag() {
            return new CompoundTag();
        }
        
        @Override
        public int setTag(final Tag kj, final Supplier<Tag> supplier) {
            return 0;
        }
        
        @Override
        public int removeTag(final Tag kj) {
            return 0;
        }
    }
}
