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

package com.hypixel.hytale.builtin.blocktick.system;

import com.hypixel.hytale.math.util.ChunkUtil;
import com.hypixel.hytale.server.core.universe.world.chunk.BlockChunk;
import com.hypixel.hytale.component.RemoveReason;
import com.hypixel.hytale.component.CommandBuffer;
import com.hypixel.hytale.component.Store;
import com.hypixel.hytale.component.AddReason;
import javax.annotation.Nonnull;
import com.hypixel.hytale.component.Ref;
import com.hypixel.hytale.component.query.Query;
import com.hypixel.hytale.server.core.universe.world.chunk.WorldChunk;
import com.hypixel.hytale.component.ComponentType;
import com.hypixel.hytale.server.core.universe.world.storage.ChunkStore;
import com.hypixel.hytale.component.system.RefSystem;

public class MergeWaitingBlocksSystem extends RefSystem<ChunkStore>
{
    private static final ComponentType<ChunkStore, WorldChunk> COMPONENT_TYPE;
    
    @Override
    public Query<ChunkStore> getQuery() {
        return MergeWaitingBlocksSystem.COMPONENT_TYPE;
    }
    
    @Override
    public void onEntityAdded(@Nonnull final Ref<ChunkStore> ref, @Nonnull final AddReason reason, @Nonnull final Store<ChunkStore> store, @Nonnull final CommandBuffer<ChunkStore> commandBuffer) {
        final ChunkStore chunkStore = store.getExternalData();
        final WorldChunk chunk = store.getComponent(ref, MergeWaitingBlocksSystem.COMPONENT_TYPE);
        final int x = chunk.getX();
        final int z = chunk.getZ();
        mergeTickingBlocks(chunkStore, x - 1, z);
        mergeTickingBlocks(chunkStore, x + 1, z);
        mergeTickingBlocks(chunkStore, x, z - 1);
        mergeTickingBlocks(chunkStore, x, z + 1);
    }
    
    @Override
    public void onEntityRemove(@Nonnull final Ref<ChunkStore> ref, @Nonnull final RemoveReason reason, @Nonnull final Store<ChunkStore> store, @Nonnull final CommandBuffer<ChunkStore> commandBuffer) {
    }
    
    public static void mergeTickingBlocks(@Nonnull final ChunkStore store, final int x, final int z) {
        final BlockChunk blockChunk = store.getChunkComponent(ChunkUtil.indexChunk(x, z), BlockChunk.getComponentType());
        if (blockChunk != null) {
            blockChunk.mergeTickingBlocks();
        }
    }
    
    static {
        COMPONENT_TYPE = WorldChunk.getComponentType();
    }
}
