package net.miarma.hystuff.commands;

import com.hypixel.hytale.component.Ref;
import com.hypixel.hytale.component.Store;
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.Universe;
import com.hypixel.hytale.server.core.universe.world.World;
import com.hypixel.hytale.server.core.universe.world.storage.EntityStore;
import net.miarma.hystuff.common.LastPositionManager;
import net.miarma.hystuff.common.Location;
import org.checkerframework.checker.nullness.compatqual.NonNullDecl;

import java.util.UUID;

public class BackCommand extends AbstractPlayerCommand {
    private final LastPositionManager lastPositionManager;

    public BackCommand(LastPositionManager lastPositionManager) {
        super("back", "Teleports you to your last position");
        this.lastPositionManager = lastPositionManager;
    }

    @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) {
        UUID playerUuid = playerRef.getUuid();
        Location lastPosition = this.lastPositionManager.get(playerUuid);

        if (!this.lastPositionManager.has(playerUuid)) {
            ctx.sendMessage(Message.raw("You don't have a last position to return to."));
        } else {
            final World targetWorld = Universe.get().getWorld(lastPosition.worldName()) != null ?
                    Universe.get().getWorld(lastPosition.worldName()) : world;

            world.execute(() -> {
                Teleport teleport = Teleport.createForPlayer(
                        targetWorld,
                        lastPosition.toPosition(),
                        lastPosition.toRotation()
                );

                store.addComponent(ref, Teleport.getComponentType(), teleport);
                ctx.sendMessage(Message.raw(String.format("Teleporting to your last position at %.1f, %.1f, %.1f",
                        lastPosition.x(), lastPosition.y(), lastPosition.z())));
            });

            this.lastPositionManager.clear(playerUuid);
        }
    }
}
