package net.miarma.hystuff.system;

import com.hypixel.hytale.component.CommandBuffer;
import com.hypixel.hytale.component.ComponentType;
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.RefChangeSystem;
import com.hypixel.hytale.server.core.modules.entity.component.TransformComponent;
import com.hypixel.hytale.server.core.modules.entity.damage.DeathComponent;
import com.hypixel.hytale.server.core.universe.PlayerRef;
import com.hypixel.hytale.server.core.universe.world.storage.EntityStore;
import net.miarma.hystuff.HyStuff;
import net.miarma.hystuff.component.LastPositionComponent;
import org.checkerframework.checker.nullness.compatqual.NonNullDecl;
import org.checkerframework.checker.nullness.compatqual.NullableDecl;

import java.util.UUID;

public class PlayerDeathSystem extends RefChangeSystem<EntityStore, DeathComponent> {
    public PlayerDeathSystem() { }

    @NonNullDecl
    @Override
    public ComponentType<EntityStore, DeathComponent> componentType() {
        return DeathComponent.getComponentType();
    }

    @Override
    public void onComponentAdded(@NonNullDecl Ref<EntityStore> ref,
                                 @NonNullDecl DeathComponent deathComponent,
                                 @NonNullDecl Store<EntityStore> store,
                                 @NonNullDecl CommandBuffer<EntityStore> commandBuffer) {
        TransformComponent transform =
                store.getComponent(ref, TransformComponent.getComponentType());

        if (transform == null) return;

        UUID worldUuid = store.getExternalData()
                .getWorld()
                .getWorldConfig()
                .getUuid();

        LastPositionComponent last = new LastPositionComponent(
                transform.getTransform().clone(),
                worldUuid
        );

        commandBuffer.putComponent(ref, HyStuff.LAST_POSITION_COMPONENT_TYPE, last);
    }

    @Override
    public void onComponentSet(@NonNullDecl Ref<EntityStore> ref, @NullableDecl DeathComponent deathComponent, @NonNullDecl DeathComponent t1, @NonNullDecl Store<EntityStore> store, @NonNullDecl CommandBuffer<EntityStore> commandBuffer) {}

    @Override
    public void onComponentRemoved(@NonNullDecl Ref<EntityStore> ref, @NonNullDecl DeathComponent deathComponent, @NonNullDecl Store<EntityStore> store, @NonNullDecl CommandBuffer<EntityStore> commandBuffer) {}

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