package net.miarma.hystuff.system;

import com.hypixel.hytale.component.ArchetypeChunk;
import com.hypixel.hytale.component.CommandBuffer;
import com.hypixel.hytale.component.Ref;
import com.hypixel.hytale.component.Store;
import com.hypixel.hytale.component.query.Query;
import com.hypixel.hytale.component.system.tick.EntityTickingSystem;
import com.hypixel.hytale.server.core.event.events.player.PlayerChatEvent;
import com.hypixel.hytale.server.core.universe.world.storage.EntityStore;
import net.miarma.hystuff.HyStuff;
import net.miarma.hystuff.component.TpaRequestComponent;
import org.checkerframework.checker.nullness.compatqual.NonNullDecl;
import org.checkerframework.checker.nullness.compatqual.NullableDecl;

public class TpaCleanupSystem extends EntityTickingSystem<EntityStore> {
    private static final long TPA_TIMEOUT_MS = 30_000;

    @NullableDecl
    @Override
    public Query<EntityStore> getQuery() {
        return HyStuff.TPA_REQUEST_COMPONENT_TYPE;
    }

    @Override
    public void tick(float dt, int i,
                     @NonNullDecl ArchetypeChunk<EntityStore> chunk,
                     @NonNullDecl Store<EntityStore> store,
                     @NonNullDecl CommandBuffer<EntityStore> commandBuffer) {
        long now = System.currentTimeMillis();
        TpaRequestComponent tpa = chunk.getComponent(i, HyStuff.TPA_REQUEST_COMPONENT_TYPE);

        if (tpa != null && now - tpa.getCreatedAt() >= TPA_TIMEOUT_MS) {
            Ref<EntityStore> entityRef = chunk.getReferenceTo(i);
            commandBuffer.removeComponent(entityRef, HyStuff.TPA_REQUEST_COMPONENT_TYPE);
        }
    }
}
