AM = {}
mod_path = "sys/lua/admin/"
mod_name = "Starkkz's Admin Script"
mod_version = "0.0.5"

parse("debuglua 0")

dofile(mod_path.."os.lua")

dofile(mod_path.."stream_functions.lua")
dofile(mod_path.."data.lua")

-- Important addons
dofile(mod_path.."addons/lua_table.lua")
dofile(mod_path.."addons/lua_math.lua")
dofile(mod_path.."addons/lua_string.lua")
dofile(mod_path.."addons/lua_funcs.lua")
dofile(mod_path.."addons/lua_error.lua")

function SetTempAddonTable(t)
	local mt = {}
	function mt.__newindex(g,k,v)
		t[k] = CopyObject(v)
	end
	
	setmetatable(_G, mt)
end

function RequireTempAddon(name)
	local f = io.open(mod_path.."addons/"..name..".lua")
	if f then
		f:close()
		print(string.char(169).."000255000Loading addon "..name)
		
		local t = {}
		SetTempAddonTable(t)
		dofile(mod_path.."addons/"..name..".lua")
		
		setmetatable(_G, nil)
		return t
	end
end

function SetAddonTable(t)
	local mt = {}
	function mt.__newindex(g,k,v)
		t[k] = v
		
		if k ~= "Init" then
			setmetatable(_G, nil)
			_G[k] = v
			
			setmetatable(_G, mt)
		end
	end
	
	setmetatable(_G, mt)
end

function RequireAddon(name)
	local f = io.open(mod_path.."addons/"..name..".lua")
	if f then
		f:close()
		print(string.char(169).."000255000Loading addon "..name)
		
		local t = {}
		SetAddonTable(t)
		dofile(mod_path.."addons/"..name..".lua")
		
		setmetatable(_G, nil)
		return t
	end
end

function LoadAddons()
	local f = io.open(mod_path.."addon_config.txt", "r")
	local temp_addon = {}
	if f then
		for lines in f:lines() do
			if string.len(lines) > 0 and string.sub(lines, 1, 2) ~= "//" then
				temp_addon[lines] = RequireAddon(lines)
			end
		end
		f:close()
	end
	
	for k, t in pairs(temp_addon) do
		if t.Init then
			t.Init()
		end
	end
	LoadAddons = nil
end; LoadAddons()

addhook("join","AM.PlayerJoin")
function AM.PlayerJoin(id)
	ReloadUSER(id)
	ReloadTEMP(id)
	LoadIPData(player(id,"ip"))
end

addhook("leave","AM.PlayerLeave")
function AM.PlayerLeave(id)
	SaveUSER(id)
	SaveIPData(player(id,"ip"))
end

addhook("mapchange","AM.GeneralSave")
function AM.GeneralSave()
	for _, id in pairs(player(0,"table")) do
		SaveUSER(id)
	end
	SaveServer()
end