--dbg.log("MOD_MAN: start")

local actor_update_func = {}
local actor_item_take_func = {}
local actor_item_drop_func = {}
local actor_car_body_func = {}
local actor_car_body_hide_func = {}
local actor_inventory_func = {}
local actor_inventory_hide_func = {}

function register_actor_update(func)
	table.insert(actor_update_func, func)
end

function register_actor_item_take(func)
	table.insert(actor_item_take_func, func)
end

function register_actor_item_drop(func)
	table.insert(actor_item_drop_func, func)
end

function register_on_actor_car_body(func)
	table.insert(actor_car_body_func, func)
end

function register_on_actor_car_body_hide(func)
	table.insert(actor_car_body_hide_func, func)
end

function register_actor_inventory(func)
	table.insert(actor_inventory_func, func)
end

function register_actor_inventory_hide(func)
	table.insert(actor_inventory_hide_func, func)
end

function on_actor_update()
	call_from_table(actor_update_func)
end

function on_actor_item_take(item)
--	dbg.log("MOD_MAN: on_actor_item_take(item=%s)", item:name())
	call_from_table(actor_item_take_func, item)
end

function on_info(info_id)
	if info_id == "ui_car_body" then
		call_from_table(actor_car_body_func)
	elseif info_id == "ui_car_body_hide" then
		call_from_table(actor_car_body_hide_func)
	elseif info_id == "ui_inventory" then
		call_from_table(actor_inventory_func)
	elseif info_id == "ui_inventory_hide" then
		call_from_table(actor_inventory_hide_func)		
	end
end

function init()
	--dbg.log("MOD_MAN: init")
	local ini = ini_file("mods.ltx")
	local s = ini:r_string("mods", "register")
	local t = str_explode(",", s, true)
	for i, v in ipairs(t) do
		--dbg.log("MOD_MAN: find mod %s", v)
		loadstring(v..".register()")()
	end
end

function call_from_table(t,...)
	for i, f in ipairs(t) do
		f(...)
	end
end

function trim (s)
	return (string.gsub(s, "^%s*(.-)%s*$", "%1"))
end

function str_explode(div,str,clear)
	local t={}
	local cpt = string.find (str, div, 1, true)
	if cpt then
		repeat
			if clear then
				table.insert( t, trim(string.sub(str, 1, cpt-1)) )
			else
				table.insert( t, string.sub(str, 1, cpt-1) )
			end
			str = string.sub( str, cpt+string.len(div) )
			cpt = string.find (str, div, 1, true)
		until cpt==nil
	end
	if clear then
		table.insert(t, trim(str))
	else
		table.insert(t, str)
	end
	return t
end
