package net.engin33r.luaspigot;

import lombok.RequiredArgsConstructor;
import net.engin33r.luaspigot.lua.Library;
import net.engin33r.luaspigot.lua.type.LuaUUID;
import org.luaj.vm2.Globals;
import org.luaj.vm2.LuaValue;
import org.luaj.vm2.Varargs;
import org.luaj.vm2.lib.OneArgFunction;
import org.luaj.vm2.lib.VarArgFunction;

import java.util.logging.Logger;

/**
 * Container for new global functions and overrides introduced for Spigot.
 */
public class SpigotGlobals {
    @RequiredArgsConstructor
    public static class Print extends VarArgFunction {
        private final Logger logger;

        public Varargs invoke(Varargs arg) {
            if (arg.narg() > 0) {
                String str = "[Lua] ";
                for (int i = 1; i <= arg.narg(); i++) {
                    if (i > 1) str += "\t";
                    str += arg.tojstring(i);
                }
                logger.info(str);
            }
            return NIL;
        }
    }

    public static class Import extends VarArgFunction {
        private final Globals env;
        private final LibraryRegistry registry;

        public Import(Globals env, LibraryRegistry registry) {
            this.env = env;
            this.registry = registry;
        }

        @Override
        public Varargs invoke(Varargs arg) {
            if (arg.narg() == 0) return NIL;

            Library lib = registry.get(arg.checkjstring(1));
            if (arg.narg() == 2)
                env.set(arg.checkjstring(2), lib.getLibrary());
            else
                env.set(lib.getName(), lib.getLibrary());

            return NIL;
        }
    }

    public static class ParseUUID extends OneArgFunction {
        @Override
        public LuaValue call(LuaValue arg) {
            return new LuaUUID(arg.checkjstring());
        }
    }
}

@@ -1368,56 +1368,212 @@
     
-Library lib = registry.get(arg.checkjstring(1));
+String name = arg.checkjstring(1);%0A            Library lib = registry.get(name);%0A            if (lib == null) %7B%0A                error(%22library not found: %22+name);%0A                return NIL;%0A            %7D
 %0A   

Add graceful failure behaviour to import()