package net.Chipperfluff.chipi.command;

import com.mojang.brigadier.CommandDispatcher;
import com.mojang.brigadier.arguments.StringArgumentType;
import com.mojang.brigadier.context.CommandContext;
import net.minecraft.command.CommandSource;
import net.minecraft.command.argument.BlockPosArgumentType;
import net.minecraft.server.command.CommandManager;
import net.minecraft.server.command.ServerCommandSource;
import net.minecraft.server.world.ServerWorld;
import net.minecraft.text.Text;
import net.minecraft.util.math.BlockPos;

import net.Chipperfluff.chipi.world.gen.struct.ChipiStructures;

public class CspCommand {

    public static void register(CommandDispatcher<ServerCommandSource> dispatcher) {
        dispatcher.register(
            CommandManager.literal("csp")
            .then(
                CommandManager.argument("name", StringArgumentType.word())
                .suggests((ctx, builder) ->
                    CommandSource.suggestMatching(ChipiStructures.getNames(), builder))
                .then(
                    CommandManager.argument("center", BlockPosArgumentType.blockPos())
                    .then(
                        CommandManager.argument("worldPos", BlockPosArgumentType.blockPos())
                        .executes(ctx -> execute(ctx))
                    )
                )
            )
        );
    }

    private static int execute(CommandContext<ServerCommandSource> ctx) {
        ServerCommandSource source = ctx.getSource();
        ServerWorld world = source.getWorld();

        String name = StringArgumentType.getString(ctx, "name");
        BlockPos center = BlockPosArgumentType.getBlockPos(ctx, "center");
        BlockPos worldPos = BlockPosArgumentType.getBlockPos(ctx, "worldPos");

        var structure = ChipiStructures.get(name);

        if (structure == null) {
            source.sendError(Text.literal("Unknown structure: " + name));
            return 0;
        }

        BlockPos local = structure.worldToLocal(center, worldPos);

        source.sendFeedback(
            () -> Text.literal(
                "localPos = (" +
                local.getX() + ", " +
                local.getY() + ", " +
                local.getZ() + ")"
            ),
            false
        );

        return 1;
    }
}
