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

package com.hypixel.hytale.server.core.modules.entity;

import com.hypixel.hytale.component.Ref;
import java.time.Instant;
import com.hypixel.hytale.component.RemoveReason;
import com.hypixel.hytale.server.core.modules.time.TimeResource;
import com.hypixel.hytale.component.CommandBuffer;
import com.hypixel.hytale.component.Store;
import com.hypixel.hytale.component.ArchetypeChunk;
import com.hypixel.hytale.server.core.modules.entity.component.Interactable;
import javax.annotation.Nonnull;
import com.hypixel.hytale.component.query.Query;
import com.hypixel.hytale.component.ComponentType;
import com.hypixel.hytale.server.core.universe.world.storage.EntityStore;
import com.hypixel.hytale.component.system.tick.EntityTickingSystem;

public class DespawnSystem extends EntityTickingSystem<EntityStore>
{
    private final ComponentType<EntityStore, DespawnComponent> despawnComponentType;
    @Nonnull
    private final Query<EntityStore> query;
    
    public DespawnSystem(final ComponentType<EntityStore, DespawnComponent> despawnComponentType) {
        this.despawnComponentType = despawnComponentType;
        this.query = (Query<EntityStore>)Query.and(despawnComponentType, Query.not((Query<Object>)Interactable.getComponentType()));
    }
    
    @Override
    public boolean isParallel(final int archetypeChunkSize, final int taskCount) {
        return EntityTickingSystem.maybeUseParallel(archetypeChunkSize, taskCount);
    }
    
    @Nonnull
    @Override
    public Query<EntityStore> getQuery() {
        return this.query;
    }
    
    @Override
    public void tick(final float dt, final int index, @Nonnull final ArchetypeChunk<EntityStore> archetypeChunk, @Nonnull final Store<EntityStore> store, @Nonnull final CommandBuffer<EntityStore> commandBuffer) {
        final DespawnComponent despawn = archetypeChunk.getComponent(index, this.despawnComponentType);
        final Instant despawnInstant = despawn.getDespawn();
        final TimeResource timeResource = store.getResource(TimeResource.getResourceType());
        if (!timeResource.getNow().isAfter(despawnInstant)) {
            return;
        }
        final Ref<EntityStore> entityRef = archetypeChunk.getReferenceTo(index);
        commandBuffer.removeEntity(entityRef, RemoveReason.REMOVE);
    }
}
