
local file_name = minetest.get_worldpath() .. "/logging.txt"
local timestamp_format = "%d/%m/%y %X"

-- init global
logging = {}

-- open the file
-- it will be closed when file is garbage-collected
local file, errmsg = io.open(file_name, "a")
if not file then
	error("[logging]: unable to open file: " .. errmsg)
end

-- logs msg to the logging file, together with a timestamp
-- category should be a static string that helps identifying what the msg is about
function logging.log(category, msg)
	file:write(string.format("(%s) [%s]: %s\n", os.date(timestamp_format), category, msg))
	file:flush()
end


-- do some basic global logging for:
-- server_start
-- server_shutdown
-- chatmessage
-- player_join (and player_join_new)
-- player_leave (and player_leave_timed_out)

logging.log("server_start", "server is started")

minetest.register_on_shutdown(function()
	logging.log("server_shutdown", "server is shut down")
end)

minetest.register_on_chat_message(function(name, msg)
	-- TODO: escape new lines and co. from the chat messages
	logging.log("chatmessage", minetest.format_chat_message(name, msg))
end)

minetest.register_on_joinplayer(function(player, last_login)
	if not last_login then
		-- player is new
		logging.log("player_join_new", "new player \"" .. player:get_player_name() .. "\" joined")
	else
		logging.log("player_join", "player \"" .. player:get_player_name() .. "\" joined")
	end
end)

minetest.register_on_leaveplayer(function(player, timed_out)
	if not timed_out then
		logging.log("player_leave", "player \"" .. player:get_player_name() .. "\" left")
	else
		logging.log("player_leave_timed_out", "player \"" .. player:get_player_name() .. "\" left (timed out)")
	end
end)
