-- run_from_4d.lua
local path = (...):match(".-\n(.-)\n")
local path2 = path .. "lib/?.lua;" .. path .. "lib/?.lx;"
path2 = path2 .. path .. "../lib/?.lua;" .. path .. "../lib/?.lx;"
path2 = path2 .. path .. "../../lib/?.lua;" .. path .. "../../lib/?.lx;"
package.path = path2
local start = require "start"

start.setFrom4d(...)

local util = require "util"
local plg = require "plugin_4d"

local luaCodeNotInUse = plg.getLongVariable("<>_lx_lNotInUse")
local loc, peg, luaFile, luaPackage

local luaAllowAlways = tostring(plg.getStringVariable("<>_lx_tAllowAlways"))
-- print("luaAllowAlways: " .. luaAllowAlways)
local function allow(methodName)
	return luaCodeNotInUse ~= 1 or luaAllowAlways:find(methodName, 1, true)
end

function runFrom4d(param)
	local methodName, debug, time, ret
	methodName, param = param:match("(.-)\n(.*)")
	if methodName ~= "server" then
		debug = plg.getLongVariable("<>_lx_lDebug")
	end
	-- print("runFrom4d:", methodName, tostring(param))
	if methodName == "unloadLua" then
		if debug == 1 then
			print("*** unloadLua")
		end
		if allow(methodName) then
			local db = require "database"
			db.disconnectAll({warn_open = false, leave_connections = 0})
		end
		return "unloadLua ok"
	elseif not allow(methodName) then
		return "" -- "not allowed: <>_lx_lNotInUse = ".. tostring(luaCodeNotInUse) ..", method: " .. methodName .. ", find: ".. tostring(luaAllowAlways:find(methodName, 1, true))
	end

	if not luaFile then
		peg = require "peg"
		loc = start.getLocal()
		luaFile = peg.parse(loc.runFrom4dFile, ".", 1)
		luaPackage = require(luaFile)
	end

	if not luaPackage then
		luaPackage = require(luaFile)
	end
	local method = luaPackage[methodName]
	local db
	if debug == 1 then
		db = require "database"
		db.showSql(true)
		time = util.seconds()
	end
	if methodName == "callTimer" then -- tag name has changed from call_method -> call_function
		param = peg.replace(param, '"call_method"', '"call_function"')
	end
	-- print("before method "..luaFile.." / "..methodName)
	ret = method(param)
	-- print("after method "..luaFile.." / "..methodName..", ret: "..tostring(ret))
	if debug == 1 then
		time = util.seconds(time)
		db.showSql(false)
		print(luaFile .. "." .. methodName .. " run time: " .. util.round(time, 4) .. " s", param, util.pathStart())
		-- elseif debug == 2 then
		-- save to file / database
	end

	return ret
end

return "ok"
