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

package com.hypixel.hytale.builtin.adventure.objectives.task;

import java.util.Collection;
import java.util.Collections;
import com.hypixel.hytale.math.vector.Vector3d;
import com.hypixel.hytale.math.util.TrigMathUtil;
import com.hypixel.hytale.math.util.MathUtil;
import javax.annotation.Nullable;
import com.hypixel.hytale.server.core.universe.world.chunk.WorldChunk;
import com.hypixel.hytale.server.core.universe.world.meta.BlockStateModule;
import com.hypixel.hytale.server.core.universe.world.meta.state.ItemContainerState;
import com.hypixel.hytale.math.util.ChunkUtil;
import com.hypixel.hytale.server.core.inventory.ItemStack;
import com.hypixel.hytale.builtin.adventure.objectives.blockstates.TreasureChestState;
import com.hypixel.hytale.math.vector.Vector3i;
import com.hypixel.hytale.protocol.packets.worldmap.ContextMenuItem;
import com.hypixel.hytale.protocol.packets.worldmap.MapMarker;
import com.hypixel.hytale.server.core.util.PositionUtil;
import com.hypixel.hytale.math.vector.Transform;
import java.util.logging.Level;
import com.hypixel.hytale.builtin.adventure.objectives.ObjectivePlugin;
import com.hypixel.hytale.server.core.universe.world.meta.BlockState;
import com.hypixel.hytale.server.core.modules.item.ItemModule;
import com.hypixel.hytale.builtin.adventure.objectives.transaction.SpawnTreasureChestTransactionRecord;
import com.hypixel.hytale.component.Ref;
import com.hypixel.hytale.component.ComponentAccessor;
import com.hypixel.hytale.builtin.adventure.objectives.transaction.RegistrationTransactionRecord;
import com.hypixel.hytale.event.IBaseEvent;
import com.hypixel.hytale.builtin.adventure.objectives.events.TreasureChestOpeningEvent;
import com.hypixel.hytale.builtin.adventure.objectives.transaction.TransactionRecord;
import com.hypixel.hytale.server.core.universe.world.storage.EntityStore;
import com.hypixel.hytale.component.Store;
import com.hypixel.hytale.server.core.universe.world.World;
import com.hypixel.hytale.builtin.adventure.objectives.Objective;
import it.unimi.dsi.fastutil.objects.ObjectArrayList;
import com.hypixel.hytale.builtin.adventure.objectives.config.task.ObjectiveTaskAsset;
import javax.annotation.Nonnull;
import com.hypixel.hytale.builtin.adventure.objectives.config.task.TreasureMapObjectiveTaskAsset;
import java.util.UUID;
import java.util.List;
import com.hypixel.hytale.codec.builder.BuilderCodec;

public class TreasureMapObjectiveTask extends ObjectiveTask
{
    public static final BuilderCodec<TreasureMapObjectiveTask> CODEC;
    public static final int CHEST_SPAWN_TRY = 500;
    private int currentCompletion;
    private int chestCount;
    private final List<UUID> chestUUIDs;
    
    public TreasureMapObjectiveTask(@Nonnull final TreasureMapObjectiveTaskAsset asset, final int taskSetIndex, final int taskIndex) {
        super(asset, taskSetIndex, taskIndex);
        this.chestUUIDs = new ObjectArrayList<UUID>();
    }
    
    protected TreasureMapObjectiveTask() {
        this.chestUUIDs = new ObjectArrayList<UUID>();
    }
    
    @Nonnull
    @Override
    public TreasureMapObjectiveTaskAsset getAsset() {
        return (TreasureMapObjectiveTaskAsset)super.getAsset();
    }
    
    @Nonnull
    public String getChestMarkerIDFromUUID(@Nonnull final UUID uuid) {
        return "TreasureChest_" + uuid.toString();
    }
    
    @Nonnull
    @Override
    protected TransactionRecord[] setup0(@Nonnull final Objective objective, @Nonnull final World world, @Nonnull final Store<EntityStore> store) {
        this.eventRegistry.register((Class<? super IBaseEvent>)TreasureChestOpeningEvent.class, world.getName(), event -> this.onTreasureChestOpeningEvent(objective, event));
        TransactionRecord[] transactionRecords = this.serializedTransactionRecords;
        if (transactionRecords != null) {
            return RegistrationTransactionRecord.append(transactionRecords, this.eventRegistry);
        }
        final TreasureMapObjectiveTaskAsset.ChestConfig[] chestConfigs = this.getAsset().getChestConfigs();
        transactionRecords = new TransactionRecord[chestConfigs.length];
        this.chestCount = chestConfigs.length;
        for (int i = 0; i < chestConfigs.length; ++i) {
            transactionRecords[i] = this.spawnChest(objective, world, chestConfigs[i], store);
        }
        return RegistrationTransactionRecord.append(transactionRecords, this.eventRegistry);
    }
    
    @Override
    public boolean checkCompletion() {
        return this.currentCompletion >= this.chestCount;
    }
    
    private void onTreasureChestOpeningEvent(@Nonnull final Objective objective, @Nonnull final TreasureChestOpeningEvent event) {
        final UUID chestUUID = event.getChestUUID();
        if (!this.chestUUIDs.contains(chestUUID)) {
            return;
        }
        ++this.currentCompletion;
        objective.markDirty();
        this.sendUpdateObjectiveTaskPacket(objective);
        final String chestMarkerID = this.getChestMarkerIDFromUUID(chestUUID);
        this.removeMarker(chestMarkerID);
        final Ref<EntityStore> playerRef = event.getPlayerRef();
        final Store<EntityStore> store = event.getStore();
        if (this.checkCompletion()) {
            this.consumeTaskConditions(store, playerRef, objective.getActivePlayerUUIDs());
            this.complete(objective, store);
            objective.checkTaskSetCompletion(store);
        }
    }
    
    @Nonnull
    private TransactionRecord spawnChest(@Nonnull final Objective objective, @Nonnull final World world, @Nonnull final TreasureMapObjectiveTaskAsset.ChestConfig chestConfig, @Nonnull final ComponentAccessor<EntityStore> componentAccessor) {
        final Vector3i conditionPosition = this.calculateChestSpawnPosition(chestConfig, objective, world, componentAccessor);
        final SpawnTreasureChestTransactionRecord transactionRecord = new SpawnTreasureChestTransactionRecord(world.getWorldConfig().getUuid(), conditionPosition);
        if (conditionPosition == null) {
            return transactionRecord.fail("Position not safe to spawn chest");
        }
        final TreasureChestState treasureChestState = this.spawnChestBlock(world, conditionPosition, chestConfig.getChestBlockTypeKey(), transactionRecord);
        if (treasureChestState == null) {
            return transactionRecord;
        }
        final UUID chestUUID = UUID.randomUUID();
        final List<ItemStack> stacks = ItemModule.get().getRandomItemDrops(chestConfig.getDroplistId());
        treasureChestState.setObjectiveData(objective.getObjectiveUUID(), chestUUID, stacks);
        this.chestUUIDs.add(chestUUID);
        treasureChestState.getChunk().setState(conditionPosition.getX(), conditionPosition.getY(), conditionPosition.getZ(), treasureChestState);
        ObjectivePlugin.get().getLogger().at(Level.INFO).log("Spawned chest at: " + String.valueOf(conditionPosition));
        this.addMarker(new MapMarker(this.getChestMarkerIDFromUUID(chestUUID), "Chest", "Home.png", PositionUtil.toTransformPacket(new Transform(conditionPosition)), null));
        return transactionRecord;
    }
    
    @Nullable
    private TreasureChestState spawnChestBlock(@Nonnull final World world, @Nonnull final Vector3i conditionPosition, final String chestBlockTypeKey, @Nonnull final SpawnTreasureChestTransactionRecord transactionRecord) {
        final WorldChunk worldChunk = world.getChunk(ChunkUtil.indexChunkFromBlock(conditionPosition.x, conditionPosition.z));
        worldChunk.setBlock(conditionPosition.x, conditionPosition.y, conditionPosition.z, chestBlockTypeKey);
        final BlockState blockState = worldChunk.getState(conditionPosition.x, conditionPosition.y, conditionPosition.z);
        if (!(blockState instanceof ItemContainerState)) {
            transactionRecord.fail("BlockState is not a container");
            return null;
        }
        final TreasureChestState treasureChestState = BlockStateModule.get().createBlockState(TreasureChestState.class, worldChunk, conditionPosition.clone(), blockState.getBlockType());
        if (treasureChestState == null) {
            transactionRecord.fail("Failed to create TreasureChestState!");
            return null;
        }
        return treasureChestState;
    }
    
    @Nullable
    private Vector3i calculateChestSpawnPosition(@Nonnull final TreasureMapObjectiveTaskAsset.ChestConfig chestConfig, @Nonnull final Objective objective, @Nonnull final World world, @Nonnull final ComponentAccessor<EntityStore> componentAccessor) {
        int currentTry;
        Vector3i conditionPosition;
        double angle;
        float radius;
        Vector3d objectivePosition;
        Vector3d position;
        for (currentTry = 0, conditionPosition = null; currentTry < 500 && conditionPosition == null; conditionPosition = chestConfig.getWorldLocationProvider().runCondition(world, position.toVector3i()), ++currentTry) {
            angle = Math.random() * 6.2831854820251465;
            radius = MathUtil.randomFloat(chestConfig.getMinRadius(), chestConfig.getMaxRadius());
            objectivePosition = objective.getPosition(componentAccessor);
            position = objectivePosition.clone().floor();
            position.add(radius * TrigMathUtil.cos(angle), 0.0, radius * TrigMathUtil.sin(angle));
            position.y = world.getChunk(ChunkUtil.indexChunkFromBlock(position.x, position.z)).getHeight(MathUtil.floor(position.x), MathUtil.floor(position.z));
        }
        return conditionPosition;
    }
    
    @Nonnull
    @Override
    public com.hypixel.hytale.protocol.ObjectiveTask toPacket(@Nonnull final Objective objective) {
        final com.hypixel.hytale.protocol.ObjectiveTask packet = new com.hypixel.hytale.protocol.ObjectiveTask();
        packet.taskDescriptionKey = this.asset.getDescriptionKey(objective.getObjectiveId(), this.taskSetIndex, this.taskIndex);
        packet.currentCompletion = this.currentCompletion;
        packet.completionNeeded = this.chestCount;
        return packet;
    }
    
    @Nonnull
    @Override
    public String toString() {
        return "TreasureMapObjectiveTask{currentCompletion=" + this.currentCompletion + ", chestCount=" + this.chestCount + ", chestUUIDs=" + String.valueOf(this.chestUUIDs) + "} " + super.toString();
    }
    
    static {
        // 
        // This method could not be decompiled.
        // 
        // Original Bytecode:
        // 
        //     2: invokedynamic   BootstrapMethod #5, get:()Ljava/util/function/Supplier;
        //     7: getstatic       com/hypixel/hytale/builtin/adventure/objectives/task/TreasureMapObjectiveTask.BASE_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           "CurrentCompletion"
        //    20: getstatic       com/hypixel/hytale/codec/Codec.INTEGER:Lcom/hypixel/hytale/codec/codecs/simple/IntegerCodec;
        //    23: invokespecial   com/hypixel/hytale/codec/KeyedCodec.<init>:(Ljava/lang/String;Lcom/hypixel/hytale/codec/Codec;)V
        //    26: invokedynamic   BootstrapMethod #6, accept:()Ljava/util/function/BiConsumer;
        //    31: invokedynamic   BootstrapMethod #7, apply:()Ljava/util/function/Function;
        //    36: invokevirtual   com/hypixel/hytale/codec/builder/BuilderCodec$Builder.append:(Lcom/hypixel/hytale/codec/KeyedCodec;Ljava/util/function/BiConsumer;Ljava/util/function/Function;)Lcom/hypixel/hytale/codec/builder/BuilderField$FieldBuilder;
        //    39: invokevirtual   com/hypixel/hytale/codec/builder/BuilderField$FieldBuilder.add:()Lcom/hypixel/hytale/codec/builder/BuilderCodec$BuilderBase;
        //    42: checkcast       Lcom/hypixel/hytale/codec/builder/BuilderCodec$Builder;
        //    45: new             Lcom/hypixel/hytale/codec/KeyedCodec;
        //    48: dup            
        //    49: ldc_w           "ChestCount"
        //    52: getstatic       com/hypixel/hytale/codec/Codec.INTEGER:Lcom/hypixel/hytale/codec/codecs/simple/IntegerCodec;
        //    55: invokespecial   com/hypixel/hytale/codec/KeyedCodec.<init>:(Ljava/lang/String;Lcom/hypixel/hytale/codec/Codec;)V
        //    58: invokedynamic   BootstrapMethod #8, accept:()Ljava/util/function/BiConsumer;
        //    63: invokedynamic   BootstrapMethod #9, apply:()Ljava/util/function/Function;
        //    68: invokevirtual   com/hypixel/hytale/codec/builder/BuilderCodec$Builder.append:(Lcom/hypixel/hytale/codec/KeyedCodec;Ljava/util/function/BiConsumer;Ljava/util/function/Function;)Lcom/hypixel/hytale/codec/builder/BuilderField$FieldBuilder;
        //    71: invokevirtual   com/hypixel/hytale/codec/builder/BuilderField$FieldBuilder.add:()Lcom/hypixel/hytale/codec/builder/BuilderCodec$BuilderBase;
        //    74: checkcast       Lcom/hypixel/hytale/codec/builder/BuilderCodec$Builder;
        //    77: new             Lcom/hypixel/hytale/codec/KeyedCodec;
        //    80: dup            
        //    81: ldc_w           "ChestUUIDs"
        //    84: new             Lcom/hypixel/hytale/codec/codecs/array/ArrayCodec;
        //    87: dup            
        //    88: getstatic       com/hypixel/hytale/codec/Codec.UUID_BINARY:Lcom/hypixel/hytale/codec/codecs/UUIDBinaryCodec;
        //    91: invokedynamic   BootstrapMethod #10, apply:()Ljava/util/function/IntFunction;
        //    96: invokespecial   com/hypixel/hytale/codec/codecs/array/ArrayCodec.<init>:(Lcom/hypixel/hytale/codec/Codec;Ljava/util/function/IntFunction;)V
        //    99: invokespecial   com/hypixel/hytale/codec/KeyedCodec.<init>:(Ljava/lang/String;Lcom/hypixel/hytale/codec/Codec;)V
        //   102: invokedynamic   BootstrapMethod #11, accept:()Ljava/util/function/BiConsumer;
        //   107: invokedynamic   BootstrapMethod #12, apply:()Ljava/util/function/Function;
        //   112: invokevirtual   com/hypixel/hytale/codec/builder/BuilderCodec$Builder.append:(Lcom/hypixel/hytale/codec/KeyedCodec;Ljava/util/function/BiConsumer;Ljava/util/function/Function;)Lcom/hypixel/hytale/codec/builder/BuilderField$FieldBuilder;
        //   115: invokevirtual   com/hypixel/hytale/codec/builder/BuilderField$FieldBuilder.add:()Lcom/hypixel/hytale/codec/builder/BuilderCodec$BuilderBase;
        //   118: checkcast       Lcom/hypixel/hytale/codec/builder/BuilderCodec$Builder;
        //   121: invokevirtual   com/hypixel/hytale/codec/builder/BuilderCodec$Builder.build:()Lcom/hypixel/hytale/codec/builder/BuilderCodec;
        //   124: putstatic       com/hypixel/hytale/builtin/adventure/objectives/task/TreasureMapObjectiveTask.CODEC:Lcom/hypixel/hytale/codec/builder/BuilderCodec;
        //   127: 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: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.runInference(TypeAnalysis.java:667)
        //     at com.strobel.decompiler.ast.TypeAnalysis.runInference(TypeAnalysis.java:373)
        //     at com.strobel.decompiler.ast.TypeAnalysis.run(TypeAnalysis.java:95)
        //     at com.strobel.decompiler.ast.AstOptimizer.optimize(AstOptimizer.java:344)
        //     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.");
    }
}
