package land.chipmunk.chipmunkmod.commands;

import com.mojang.brigadier.Command;
import com.mojang.brigadier.CommandDispatcher;
import com.mojang.brigadier.context.CommandContext;
import net.fabricmc.fabric.api.client.command.v2.FabricClientCommandSource;
import net.minecraft.ChatFormatting;
import net.minecraft.client.Minecraft;
import net.minecraft.network.chat.Component;
import org.luaj.vm2.Globals;
import org.luaj.vm2.LuaValue;
import org.luaj.vm2.lib.jse.CoerceJavaToLua;
import org.luaj.vm2.lib.jse.JsePlatform;

import static com.mojang.brigadier.arguments.StringArgumentType.getString;
import static com.mojang.brigadier.arguments.StringArgumentType.greedyString;
import static land.chipmunk.chipmunkmod.command.CommandManager.argument;
import static land.chipmunk.chipmunkmod.command.CommandManager.literal;

public class EvalCommand {
    public static void register (final CommandDispatcher<FabricClientCommandSource> dispatcher) {
        dispatcher.register(
                literal("eval")
                        .then(argument("code", greedyString())
                                      .executes(EvalCommand::eval))
        );
    }

    public static int eval (final CommandContext<FabricClientCommandSource> context) {
        final String code = getString(context, "code");

        try {
            final Globals globals = JsePlatform.standardGlobals();

            globals.set("client", CoerceJavaToLua.coerce(Minecraft.getInstance()));
            globals.set("context", CoerceJavaToLua.coerce(context));
            globals.set("class", CoerceJavaToLua.coerce(Class.class));

            final LuaValue chunk = globals.load(code);

            context.getSource().sendFeedback(Component.literal(chunk.call().toString()).withStyle(ChatFormatting.GREEN));
        } catch (final Exception e) {
            context.getSource().sendError(Component.literal(e.toString()));
        }

        return Command.SINGLE_SUCCESS;
    }
}
