the_end_game_master = {}


local modpath = minetest.get_modpath("the_end_game_master")

the_end_game_master.intramod = {}
local storage = minetest.get_mod_storage()
local stage = storage:get_string("stage")

the_end_game_master.intramod.storage = storage

dofile(modpath .. "/game_watcher.lua")
dofile(modpath .. "/pregame.lua")
dofile(modpath .. "/game.lua")
the_end_game_master.intramod = nil





function the_end_game_master.clear_mobs()
	minetest.clear_objects({mode = "full"})
end


function the_end_game_master.set_stage(s)
	stage = s
	storage:set_string("stage", s)
end

function the_end_game_master.get_stage()
	return stage
end

if stage == ""
then
	the_end_game_master.set_pregame()
elseif stage == "pregame" or stage == "loading"
then
	the_end_game_master.set_pregame()
elseif stage == "game"
then
	in_game_guide.set_root_page("the_end_gameplay_guide_master:home")
	mob_spawning_director.enable()
	sfinv.enabled = true
end


minetest.register_on_player_hpchange(function(player, change, reason)
		if stage ~= "game" and reason.type ~= "respawn"
		then
			return 0
		else
			return change
		end
	end, true)









--each game is given an id that is used to detect when a player is new

local game_id = storage:get_int("game_id")

function the_end_game_master.get_game_id()
	return game_id
end

function the_end_game_master.increase_game_id()
	game_id = game_id + 1
	storage:set_int("game_id", game_id)
end

local function store_game_id_in_playermeta(player)
	local meta = player:get_meta()
	meta:set_int("last_game_played", game_id)
end

minetest.register_on_leaveplayer(store_game_id_in_playermeta)

minetest.register_on_shutdown(function()
		for _, p in ipairs(minetest.get_connected_players())
		do
			store_game_id_in_playermeta(p)
		end
	end)




minetest.register_on_joinplayer(function(player)
		local meta = player:get_meta()
		local gid = meta:get_int("last_game_played")

	if gid ~= game_id
		then
			limbo_respawning.return_from_limbo(player)

			if stage == "game"
			then
				give_initial_stuff.give(player)
			end
		end
	end)


--removing mobs that weren't loaded when a game ended
defense_mob_api.register_on_default_get_staticdata(function(self)
		return "the_end_game", game_id
	end)

defense_mob_api.register_on_default_activate(function(self, staticdata)
		local data = minetest.deserialize(staticdata)

		if data and data.the_end_game and data.the_end_game ~= game_id
		then
			self:remove()
		end
	end)
