package net.miarma.hystuff.commands;

import com.hypixel.hytale.component.Ref;
import com.hypixel.hytale.component.Store;
import com.hypixel.hytale.math.vector.Vector3d;
import com.hypixel.hytale.math.vector.Vector3f;
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.HeadRotation;
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.common.HomeManager;

import javax.annotation.Nonnull;
import java.util.UUID;

public class SetHomeCommand extends AbstractPlayerCommand {
    private final HomeManager homeManager;

    public SetHomeCommand(@Nonnull HomeManager homeManager) {
        super("sethome", "Set your home location");
        this.homeManager = homeManager;
    }

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

    @Override
    protected void execute(@Nonnull CommandContext ctx,
                           @Nonnull Store<EntityStore> store,
                           @Nonnull Ref<EntityStore> ref,
                           @Nonnull PlayerRef playerRef,
                           @Nonnull World world) {
        TransformComponent transform = store.getComponent(ref, TransformComponent.getComponentType());
        if (transform == null) {
            ctx.sendMessage(Message.raw("Could not get your position."));
        } else {
            HeadRotation headRotation = store.getComponent(ref, HeadRotation.getComponentType());
            Vector3f rotation = headRotation.getRotation();
            Vector3d position = transform.getPosition();
            UUID playerUuid = playerRef.getUuid();
            this.homeManager.setHome(playerUuid, world, position, rotation);
            ctx.sendMessage(Message.raw(String.format("Home set at %.1f, %.1f, %.1f in %s",
                    position.getX(), position.getY(), position.getZ(), world.getName())));
        }
    }
}
