package net.miarma.hystuff.commands.misc;

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.component.TransformComponent;
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.HomeComponent;

import javax.annotation.Nonnull;

public class SetHomeCommand extends AbstractPlayerCommand {

    public SetHomeCommand() {
        super("sethome", "Set your home location");
    }

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

    @Override
    protected void execute(@Nonnull CommandContext ctx,
                           @Nonnull Store<EntityStore> store,
                           @Nonnull Ref<EntityStore> ref,
                           @Nonnull PlayerRef player,
                           @Nonnull World world) {

        TransformComponent transformComp =
                store.getComponent(ref, TransformComponent.getComponentType());

        if (transformComp == null) {
            ctx.sendMessage(Message.raw("Could not get your current position!"));
            return;
        }

        HomeComponent home = new HomeComponent(
            transformComp.getTransform().clone(),
            world.getWorldConfig().getUuid()
        );

        world.execute(() -> {
            store.putComponent(ref, HyStuff.HOME_COMPONENT_TYPE, home);
        });

        ctx.sendMessage(Message.raw(String.format(
            "Your home has been set at %.1f, %.1f, %.1f",
            transformComp.getPosition().getX(),
            transformComp.getPosition().getY(),
            transformComp.getPosition().getZ()
        )));
    }
}
