--[[ Development Mode
This is a special gamestate that allows to change the game
world at will without interference. Features:
* Access to getitem
* Nothing is protected
* No laser updates
* Large inventory ]]

local S = minetest.get_translator("lzr_devmode")

lzr_gamestate.register_on_enter_state(function(new_state)
	if new_state ~= lzr_gamestate.DEV then
		return
	end
	local player = minetest.get_player_by_name("singleplayer")
	if not player or not player:is_player() then
		return
	end
	lzr_gui.set_dev_gui(player)
	lzr_player.set_dev_inventory(player)
	lzr_privs.grant_edit_privs(player)
end)

lzr_gamestate.register_on_exit_state(function(state)
	if state ~= lzr_gamestate.DEV then
		return
	end
	local new_state = lzr_gamestate.get_state()
	if new_state ~= lzr_gamestate.EDITOR then
		local player = minetest.get_player_by_name("singleplayer")
		if player then
			lzr_privs.revoke_edit_privs(player)
		end
	end
end)

-- Add /devmode command, but only if the hidden lzr_debug setting is active
if minetest.settings:get_bool("lzr_debug", false) then
	minetest.register_chatcommand("devmode", {
		description = S("Enter the development mode"),
		privs = { server = true },
		params = "",
		func = function(name, param)
			local player = minetest.get_player_by_name(name)
			local already_in = lzr_gamestate.get_state() == lzr_gamestate.DEV
			if not already_in then
				lzr_gamestate.set_state(lzr_gamestate.DEV)
				return true
			else
				return false, S("Already in development mode!")
			end
			return false
		end,
	})
end

minetest.register_on_player_receive_fields(function(player, formname, fields)
	if fields.__lzr_devmode_get_item then
		local pname = player:get_player_name()
		lzr_getitem.show_formspec(pname)
	end
end)

-- Unlimited node placement in dev mode
minetest.register_on_placenode(function(pos, newnode, placer, oldnode, itemstack)
	if placer and placer:is_player() then
		return lzr_gamestate.get_state() == lzr_gamestate.DEV
	end
end)

-- Don't pick node up if the item is already in the inventory
local old_handle_node_drops = minetest.handle_node_drops
function minetest.handle_node_drops(pos, drops, digger)
	if not digger or not digger:is_player() or
		lzr_gamestate.get_state() ~= lzr_gamestate.DEV then
		return old_handle_node_drops(pos, drops, digger)
	end
	local inv = digger:get_inventory()
	if inv then
		for _, item in ipairs(drops) do
			if not inv:contains_item("main", item, true) then
				inv:add_item("main", item)
			end
		end
	end
end

