package net.miarma.hystuff.commands.misc;

import com.hypixel.hytale.component.Ref;
import com.hypixel.hytale.component.Store;
import com.hypixel.hytale.math.vector.Transform;
import com.hypixel.hytale.server.core.Message;
import com.hypixel.hytale.server.core.command.system.CommandContext;
import com.hypixel.hytale.server.core.command.system.basecommands.AbstractPlayerCommand;
import com.hypixel.hytale.server.core.modules.entity.teleport.Teleport;
import com.hypixel.hytale.server.core.universe.PlayerRef;
import com.hypixel.hytale.server.core.universe.world.World;
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;

public class BackCommand extends AbstractPlayerCommand {

    public BackCommand() {
        super("back", "Teleports you to your last position");
    }

    @Override
    protected boolean canGeneratePermission() {
        return false;
    }

    @Override
    protected void execute(@NonNullDecl CommandContext ctx,
                           @NonNullDecl Store<EntityStore> store,
                           @NonNullDecl Ref<EntityStore> ref,
                           @NonNullDecl PlayerRef playerRef,
                           @NonNullDecl World world) {
        LastPositionComponent lastComp = store.getComponent(ref, HyStuff.LAST_POSITION_COMPONENT_TYPE);

        if (lastComp == null) {
            ctx.sendMessage(Message.raw("No hay posición anterior"));
            return;
        }

        Transform lastLocation = lastComp.getTransform();

        Teleport teleport = new Teleport(lastLocation.getPosition(), lastLocation.getRotation());

        world.execute(() -> {
            store.addComponent(ref, Teleport.getComponentType(), teleport);
            store.removeComponent(ref, HyStuff.LAST_POSITION_COMPONENT_TYPE);
        });
    }
}
