// 
// Decompiled by Procyon v0.6.0
// 

package com.hypixel.hytale.builtin.adventure.farming.interactions;

import com.hypixel.hytale.server.core.universe.world.storage.ChunkStore;
import com.hypixel.hytale.server.core.universe.world.chunk.WorldChunk;
import com.hypixel.hytale.protocol.BlockPosition;
import com.hypixel.hytale.function.consumer.TriConsumer;
import com.hypixel.hytale.server.core.asset.type.model.config.Model;
import com.hypixel.hytale.component.Store;
import com.hypixel.hytale.math.vector.Vector3f;
import com.hypixel.hytale.server.core.asset.type.blocktype.config.BlockFace;
import com.hypixel.hytale.math.vector.Vector3d;
import com.hypixel.hytale.server.core.modules.time.WorldTimeResource;
import com.hypixel.hytale.builtin.adventure.farming.states.CoopBlock;
import org.bson.BsonDocument;
import com.hypixel.hytale.server.core.modules.block.BlockModule;
import com.hypixel.hytale.math.util.ChunkUtil;
import com.hypixel.hytale.math.vector.Vector3i;
import javax.annotation.Nullable;
import com.hypixel.hytale.server.core.universe.world.World;
import com.hypixel.hytale.server.core.inventory.Inventory;
import com.hypixel.hytale.server.core.entity.Entity;
import com.hypixel.hytale.component.Ref;
import com.hypixel.hytale.server.core.inventory.ItemStack;
import com.hypixel.hytale.component.CommandBuffer;
import com.hypixel.hytale.component.RemoveReason;
import com.hypixel.hytale.server.npc.NPCPlugin;
import com.hypixel.hytale.server.core.asset.type.model.config.ModelAsset;
import com.hypixel.hytale.server.core.modules.entity.component.PersistentModel;
import com.hypixel.hytale.builtin.tagset.TagSetPlugin;
import com.hypixel.hytale.builtin.tagset.config.NPCGroup;
import com.hypixel.hytale.server.npc.entities.NPCEntity;
import com.hypixel.hytale.codec.Codec;
import com.hypixel.hytale.server.npc.metadata.CapturedNPCMetadata;
import com.hypixel.hytale.server.core.entity.LivingEntity;
import com.hypixel.hytale.server.core.universe.world.storage.EntityStore;
import com.hypixel.hytale.component.ComponentAccessor;
import com.hypixel.hytale.server.core.entity.EntityUtils;
import com.hypixel.hytale.protocol.InteractionState;
import com.hypixel.hytale.server.core.modules.interaction.interaction.CooldownHandler;
import com.hypixel.hytale.server.core.entity.InteractionContext;
import javax.annotation.Nonnull;
import com.hypixel.hytale.protocol.InteractionType;
import com.hypixel.hytale.codec.builder.BuilderCodec;
import com.hypixel.hytale.server.core.modules.interaction.interaction.config.client.SimpleBlockInteraction;

public class UseCaptureCrateInteraction extends SimpleBlockInteraction
{
    public static final BuilderCodec<UseCaptureCrateInteraction> CODEC;
    protected String[] acceptedNpcGroupIds;
    protected int[] acceptedNpcGroupIndexes;
    protected String fullIcon;
    
    @Override
    protected void tick0(final boolean firstRun, final float time, @Nonnull final InteractionType type, @Nonnull final InteractionContext context, @Nonnull final CooldownHandler cooldownHandler) {
        final CommandBuffer<EntityStore> commandBuffer = context.getCommandBuffer();
        if (commandBuffer == null) {
            context.getState().state = InteractionState.Failed;
            return;
        }
        final ItemStack item = context.getHeldItem();
        if (item == null) {
            context.getState().state = InteractionState.Failed;
            return;
        }
        final Ref<EntityStore> ref = context.getEntity();
        final Entity entity = EntityUtils.getEntity(ref, commandBuffer);
        if (!(entity instanceof LivingEntity)) {
            context.getState().state = InteractionState.Failed;
            return;
        }
        final LivingEntity livingEntity = (LivingEntity)entity;
        final Inventory inventory = livingEntity.getInventory();
        final byte activeHotbarSlot = inventory.getActiveHotbarSlot();
        final ItemStack inHandItemStack = inventory.getActiveHotbarItem();
        final CapturedNPCMetadata existingMeta = item.getFromMetadataOrNull("CapturedEntity", CapturedNPCMetadata.CODEC);
        if (existingMeta != null) {
            super.tick0(firstRun, time, type, context, cooldownHandler);
            return;
        }
        final Ref<EntityStore> targetEntity = context.getTargetEntity();
        if (targetEntity == null) {
            context.getState().state = InteractionState.Failed;
            return;
        }
        final NPCEntity npcComponent = commandBuffer.getComponent(targetEntity, NPCEntity.getComponentType());
        if (npcComponent == null) {
            context.getState().state = InteractionState.Failed;
            return;
        }
        final TagSetPlugin.TagSetLookup tagSetPlugin = TagSetPlugin.get(NPCGroup.class);
        boolean tagFound = false;
        for (final int group : this.acceptedNpcGroupIndexes) {
            if (tagSetPlugin.tagInSet(group, npcComponent.getRoleIndex())) {
                tagFound = true;
                break;
            }
        }
        if (!tagFound) {
            context.getState().state = InteractionState.Failed;
            return;
        }
        final PersistentModel persistentModel = commandBuffer.getComponent(targetEntity, PersistentModel.getComponentType());
        if (persistentModel == null) {
            context.getState().state = InteractionState.Failed;
            return;
        }
        final ModelAsset modelAsset = ModelAsset.getAssetMap().getAsset(persistentModel.getModelReference().getModelAssetId());
        final CapturedNPCMetadata meta = inHandItemStack.getFromMetadataOrDefault("CapturedEntity", CapturedNPCMetadata.CODEC);
        if (modelAsset != null) {
            meta.setIconPath(modelAsset.getIcon());
        }
        meta.setRoleIndex(npcComponent.getRoleIndex());
        final String npcName = NPCPlugin.get().getName(npcComponent.getRoleIndex());
        if (npcName != null) {
            meta.setNpcNameKey(npcName);
        }
        if (this.fullIcon != null) {
            meta.setFullItemIcon(this.fullIcon);
        }
        final ItemStack itemWithNPC = inHandItemStack.withMetadata(CapturedNPCMetadata.KEYED_CODEC, meta);
        inventory.getHotbar().replaceItemStackInSlot(activeHotbarSlot, item, itemWithNPC);
        commandBuffer.removeEntity(targetEntity, RemoveReason.REMOVE);
    }
    
    @Override
    protected void interactWithBlock(@Nonnull final World world, @Nonnull final CommandBuffer<EntityStore> commandBuffer, @Nonnull final InteractionType type, @Nonnull final InteractionContext context, @Nullable final ItemStack itemInHand, @Nonnull final Vector3i targetBlock, @Nonnull final CooldownHandler cooldownHandler) {
        final ItemStack item = context.getHeldItem();
        if (item == null) {
            context.getState().state = InteractionState.Failed;
            return;
        }
        final Ref<EntityStore> ref = context.getEntity();
        final Entity entity = EntityUtils.getEntity(ref, commandBuffer);
        if (!(entity instanceof LivingEntity)) {
            context.getState().state = InteractionState.Failed;
            return;
        }
        final LivingEntity livingEntity = (LivingEntity)entity;
        final Inventory inventory = livingEntity.getInventory();
        final byte activeHotbarSlot = inventory.getActiveHotbarSlot();
        final CapturedNPCMetadata existingMeta = item.getFromMetadataOrNull("CapturedEntity", CapturedNPCMetadata.CODEC);
        if (existingMeta == null) {
            context.getState().state = InteractionState.Failed;
            return;
        }
        final BlockPosition pos = context.getTargetBlock();
        if (pos == null) {
            context.getState().state = InteractionState.Failed;
            return;
        }
        final WorldChunk worldChunk = world.getChunk(ChunkUtil.indexChunkFromBlock(pos.x, pos.z));
        Ref<ChunkStore> blockRef = worldChunk.getBlockComponentEntity(pos.x, pos.y, pos.z);
        if (blockRef == null) {
            blockRef = BlockModule.ensureBlockEntity(worldChunk, pos.x, pos.y, pos.z);
        }
        final ItemStack noMetaItemStack = item.withMetadata(null);
        if (blockRef != null) {
            final Store<ChunkStore> chunkStore = world.getChunkStore().getStore();
            final CoopBlock coopBlockState = chunkStore.getComponent(blockRef, CoopBlock.getComponentType());
            if (coopBlockState != null) {
                final WorldTimeResource worldTimeResource = commandBuffer.getResource(WorldTimeResource.getResourceType());
                if (coopBlockState.tryPutResident(existingMeta, worldTimeResource)) {
                    world.execute(() -> coopBlockState.ensureSpawnResidentsInWorld(world, world.getEntityStore().getStore(), new Vector3d(pos.x, pos.y, pos.z), new Vector3d().assign(Vector3d.FORWARD)));
                    inventory.getHotbar().replaceItemStackInSlot(activeHotbarSlot, item, noMetaItemStack);
                }
                else {
                    context.getState().state = InteractionState.Failed;
                }
                return;
            }
        }
        final Vector3d spawnPos = new Vector3d(pos.x + 0.5f, pos.y, pos.z + 0.5f);
        if (context.getClientState() != null) {
            final BlockFace blockFace = BlockFace.fromProtocolFace(context.getClientState().blockFace);
            if (blockFace != null) {
                spawnPos.add(blockFace.getDirection());
            }
        }
        final NPCPlugin npcModule = NPCPlugin.get();
        final Store<EntityStore> store = context.getCommandBuffer().getStore();
        final int roleIndex = existingMeta.getRoleIndex();
        commandBuffer.run(_store -> npcModule.spawnEntity(store, roleIndex, spawnPos, Vector3f.ZERO, null, null));
        inventory.getHotbar().replaceItemStackInSlot(activeHotbarSlot, item, noMetaItemStack);
    }
    
    @Override
    protected void simulateInteractWithBlock(@Nonnull final InteractionType type, @Nonnull final InteractionContext context, @Nullable final ItemStack itemInHand, @Nonnull final World world, @Nonnull final Vector3i targetBlock) {
    }
    
    static {
        // 
        // This method could not be decompiled.
        // 
        // Original Bytecode:
        // 
        //     2: invokedynamic   BootstrapMethod #2, get:()Ljava/util/function/Supplier;
        //     7: getstatic       com/hypixel/hytale/server/core/modules/interaction/interaction/config/SimpleInteraction.CODEC:Lcom/hypixel/hytale/codec/builder/BuilderCodec;
        //    10: invokestatic    com/hypixel/hytale/codec/builder/BuilderCodec.builder:(Ljava/lang/Class;Ljava/util/function/Supplier;Lcom/hypixel/hytale/codec/builder/BuilderCodec;)Lcom/hypixel/hytale/codec/builder/BuilderCodec$Builder;
        //    13: new             Lcom/hypixel/hytale/codec/KeyedCodec;
        //    16: dup            
        //    17: ldc_w           "AcceptedNpcGroups"
        //    20: getstatic       com/hypixel/hytale/builtin/tagset/config/NPCGroup.CHILD_ASSET_CODEC_ARRAY:Lcom/hypixel/hytale/codec/Codec;
        //    23: invokespecial   com/hypixel/hytale/codec/KeyedCodec.<init>:(Ljava/lang/String;Lcom/hypixel/hytale/codec/Codec;)V
        //    26: invokedynamic   BootstrapMethod #3, accept:()Ljava/util/function/BiConsumer;
        //    31: invokedynamic   BootstrapMethod #4, apply:()Ljava/util/function/Function;
        //    36: invokedynamic   BootstrapMethod #5, accept:()Ljava/util/function/BiConsumer;
        //    41: invokevirtual   com/hypixel/hytale/codec/builder/BuilderCodec$Builder.appendInherited:(Lcom/hypixel/hytale/codec/KeyedCodec;Ljava/util/function/BiConsumer;Ljava/util/function/Function;Ljava/util/function/BiConsumer;)Lcom/hypixel/hytale/codec/builder/BuilderField$FieldBuilder;
        //    44: getstatic       com/hypixel/hytale/builtin/tagset/config/NPCGroup.VALIDATOR_CACHE:Lcom/hypixel/hytale/codec/validation/ValidatorCache;
        //    47: invokevirtual   com/hypixel/hytale/codec/validation/ValidatorCache.getArrayValidator:()Lcom/hypixel/hytale/codec/validation/validator/ArrayValidator;
        //    50: invokevirtual   com/hypixel/hytale/codec/builder/BuilderField$FieldBuilder.addValidator:(Lcom/hypixel/hytale/codec/validation/Validator;)Lcom/hypixel/hytale/codec/builder/BuilderField$FieldBuilder;
        //    53: invokevirtual   com/hypixel/hytale/codec/builder/BuilderField$FieldBuilder.add:()Lcom/hypixel/hytale/codec/builder/BuilderCodec$BuilderBase;
        //    56: checkcast       Lcom/hypixel/hytale/codec/builder/BuilderCodec$Builder;
        //    59: new             Lcom/hypixel/hytale/codec/KeyedCodec;
        //    62: dup            
        //    63: ldc_w           "FullIcon"
        //    66: getstatic       com/hypixel/hytale/codec/Codec.STRING:Lcom/hypixel/hytale/codec/codecs/simple/StringCodec;
        //    69: invokespecial   com/hypixel/hytale/codec/KeyedCodec.<init>:(Ljava/lang/String;Lcom/hypixel/hytale/codec/Codec;)V
        //    72: invokedynamic   BootstrapMethod #6, accept:()Ljava/util/function/BiConsumer;
        //    77: invokedynamic   BootstrapMethod #7, apply:()Ljava/util/function/Function;
        //    82: invokedynamic   BootstrapMethod #8, accept:()Ljava/util/function/BiConsumer;
        //    87: invokevirtual   com/hypixel/hytale/codec/builder/BuilderCodec$Builder.appendInherited:(Lcom/hypixel/hytale/codec/KeyedCodec;Ljava/util/function/BiConsumer;Ljava/util/function/Function;Ljava/util/function/BiConsumer;)Lcom/hypixel/hytale/codec/builder/BuilderField$FieldBuilder;
        //    90: invokevirtual   com/hypixel/hytale/codec/builder/BuilderField$FieldBuilder.add:()Lcom/hypixel/hytale/codec/builder/BuilderCodec$BuilderBase;
        //    93: checkcast       Lcom/hypixel/hytale/codec/builder/BuilderCodec$Builder;
        //    96: invokedynamic   BootstrapMethod #9, accept:()Ljava/util/function/Consumer;
        //   101: invokevirtual   com/hypixel/hytale/codec/builder/BuilderCodec$Builder.afterDecode:(Ljava/util/function/Consumer;)Lcom/hypixel/hytale/codec/builder/BuilderCodec$BuilderBase;
        //   104: checkcast       Lcom/hypixel/hytale/codec/builder/BuilderCodec$Builder;
        //   107: invokevirtual   com/hypixel/hytale/codec/builder/BuilderCodec$Builder.build:()Lcom/hypixel/hytale/codec/builder/BuilderCodec;
        //   110: putstatic       com/hypixel/hytale/builtin/adventure/farming/interactions/UseCaptureCrateInteraction.CODEC:Lcom/hypixel/hytale/codec/builder/BuilderCodec;
        //   113: return         
        // 
        // The error that occurred was:
        // 
        // java.lang.UnsupportedOperationException: The requested operation is not supported.
        //     at com.strobel.util.ContractUtils.unsupported(ContractUtils.java:27)
        //     at com.strobel.assembler.metadata.TypeReference.getRawType(TypeReference.java:284)
        //     at com.strobel.assembler.metadata.TypeReference.getRawType(TypeReference.java:279)
        //     at com.strobel.assembler.metadata.TypeReference.makeGenericType(TypeReference.java:154)
        //     at com.strobel.assembler.metadata.TypeSubstitutionVisitor.visitParameterizedType(TypeSubstitutionVisitor.java:225)
        //     at com.strobel.assembler.metadata.TypeSubstitutionVisitor.visitParameterizedType(TypeSubstitutionVisitor.java:25)
        //     at com.strobel.assembler.metadata.ParameterizedType.accept(ParameterizedType.java:103)
        //     at com.strobel.assembler.metadata.TypeSubstitutionVisitor.visit(TypeSubstitutionVisitor.java:40)
        //     at com.strobel.assembler.metadata.TypeSubstitutionVisitor.visitParameterizedType(TypeSubstitutionVisitor.java:211)
        //     at com.strobel.assembler.metadata.TypeSubstitutionVisitor.visitParameterizedType(TypeSubstitutionVisitor.java:25)
        //     at com.strobel.assembler.metadata.ParameterizedType.accept(ParameterizedType.java:103)
        //     at com.strobel.assembler.metadata.TypeSubstitutionVisitor.visit(TypeSubstitutionVisitor.java:40)
        //     at com.strobel.assembler.metadata.TypeSubstitutionVisitor.visitMethod(TypeSubstitutionVisitor.java:314)
        //     at com.strobel.decompiler.ast.TypeAnalysis.inferCall(TypeAnalysis.java:2611)
        //     at com.strobel.decompiler.ast.TypeAnalysis.doInferTypeForExpression(TypeAnalysis.java:1040)
        //     at com.strobel.decompiler.ast.TypeAnalysis.inferTypeForExpression(TypeAnalysis.java:815)
        //     at com.strobel.decompiler.ast.TypeAnalysis.inferTypeForExpression(TypeAnalysis.java:790)
        //     at com.strobel.decompiler.ast.TypeAnalysis.inferCall(TypeAnalysis.java:2689)
        //     at com.strobel.decompiler.ast.TypeAnalysis.doInferTypeForExpression(TypeAnalysis.java:1040)
        //     at com.strobel.decompiler.ast.TypeAnalysis.inferTypeForExpression(TypeAnalysis.java:815)
        //     at com.strobel.decompiler.ast.TypeAnalysis.inferTypeForExpression(TypeAnalysis.java:782)
        //     at com.strobel.decompiler.ast.TypeAnalysis.inferTypeForExpression(TypeAnalysis.java:778)
        //     at com.strobel.decompiler.ast.TypeAnalysis.doInferTypeForExpression(TypeAnalysis.java:1510)
        //     at com.strobel.decompiler.ast.TypeAnalysis.inferTypeForExpression(TypeAnalysis.java:815)
        //     at com.strobel.decompiler.ast.TypeAnalysis.inferTypeForExpression(TypeAnalysis.java:790)
        //     at com.strobel.decompiler.ast.TypeAnalysis.inferCall(TypeAnalysis.java:2689)
        //     at com.strobel.decompiler.ast.TypeAnalysis.doInferTypeForExpression(TypeAnalysis.java:1040)
        //     at com.strobel.decompiler.ast.TypeAnalysis.inferTypeForExpression(TypeAnalysis.java:815)
        //     at com.strobel.decompiler.ast.TypeAnalysis.inferTypeForExpression(TypeAnalysis.java:782)
        //     at com.strobel.decompiler.ast.TypeAnalysis.inferTypeForExpression(TypeAnalysis.java:778)
        //     at com.strobel.decompiler.ast.TypeAnalysis.doInferTypeForExpression(TypeAnalysis.java:1510)
        //     at com.strobel.decompiler.ast.TypeAnalysis.inferTypeForExpression(TypeAnalysis.java:815)
        //     at com.strobel.decompiler.ast.TypeAnalysis.inferTypeForExpression(TypeAnalysis.java:790)
        //     at com.strobel.decompiler.ast.TypeAnalysis.inferCall(TypeAnalysis.java:2689)
        //     at com.strobel.decompiler.ast.TypeAnalysis.doInferTypeForExpression(TypeAnalysis.java:1040)
        //     at com.strobel.decompiler.ast.TypeAnalysis.inferTypeForExpression(TypeAnalysis.java:815)
        //     at com.strobel.decompiler.ast.TypeAnalysis.inferTypeForExpression(TypeAnalysis.java:782)
        //     at com.strobel.decompiler.ast.TypeAnalysis.inferTypeForExpression(TypeAnalysis.java:778)
        //     at com.strobel.decompiler.ast.TypeAnalysis.doInferTypeForExpression(TypeAnalysis.java:1083)
        //     at com.strobel.decompiler.ast.TypeAnalysis.inferTypeForExpression(TypeAnalysis.java:815)
        //     at com.strobel.decompiler.ast.TypeAnalysis.runInference(TypeAnalysis.java:684)
        //     at com.strobel.decompiler.ast.TypeAnalysis.inferTypesForVariables(TypeAnalysis.java:593)
        //     at com.strobel.decompiler.ast.TypeAnalysis.runInference(TypeAnalysis.java:405)
        //     at com.strobel.decompiler.ast.TypeAnalysis.run(TypeAnalysis.java:95)
        //     at com.strobel.decompiler.ast.AstOptimizer.optimize(AstOptimizer.java:109)
        //     at com.strobel.decompiler.ast.AstOptimizer.optimize(AstOptimizer.java:42)
        //     at com.strobel.decompiler.languages.java.ast.AstMethodBodyBuilder.createMethodBody(AstMethodBodyBuilder.java:206)
        //     at com.strobel.decompiler.languages.java.ast.AstMethodBodyBuilder.createMethodBody(AstMethodBodyBuilder.java:93)
        //     at com.strobel.decompiler.languages.java.ast.AstBuilder.createMethodBody(AstBuilder.java:868)
        //     at com.strobel.decompiler.languages.java.ast.AstBuilder.createMethod(AstBuilder.java:761)
        //     at com.strobel.decompiler.languages.java.ast.AstBuilder.addTypeMembers(AstBuilder.java:638)
        //     at com.strobel.decompiler.languages.java.ast.AstBuilder.createTypeCore(AstBuilder.java:605)
        //     at com.strobel.decompiler.languages.java.ast.AstBuilder.createTypeNoCache(AstBuilder.java:195)
        //     at com.strobel.decompiler.languages.java.ast.AstBuilder.createType(AstBuilder.java:162)
        //     at com.strobel.decompiler.languages.java.ast.AstBuilder.addType(AstBuilder.java:137)
        //     at com.strobel.decompiler.languages.java.JavaLanguage.buildAst(JavaLanguage.java:71)
        //     at com.strobel.decompiler.languages.java.JavaLanguage.decompileType(JavaLanguage.java:59)
        //     at com.strobel.decompiler.DecompilerDriver.decompileType(DecompilerDriver.java:333)
        //     at com.strobel.decompiler.DecompilerDriver.decompileJar(DecompilerDriver.java:254)
        //     at com.strobel.decompiler.DecompilerDriver.main(DecompilerDriver.java:129)
        // 
        throw new IllegalStateException("An error occurred while decompiling this method.");
    }
}
