-- bones/init.lua

-- Minetest 0.4 mod: bones
-- See README.txt for licensing and other information.

-- Load support for MT game translation.
local S = minetest.get_translator("leaveghost")

local bones = {}
leaveghost=bones

local function is_owner(pos, name)
	local owner = minetest.get_meta(pos):get_string("owner")
	if owner == "" or owner == name or minetest.check_player_privs(name, "protection_bypass") then
		return true
	end
	return false
end

local bones_formspec =
	"size[11,9]" ..
	"list[current_name;main;0,0.3;8,4;]" ..
	"list[current_name;craft;8,0.3;3,3;]" ..
	(armor and "list[current_name;armor;8,3.3;3,2;]" or "") ..
	"list[current_player;main;0,4.85;8,1;]" ..
	"list[current_player;main;0,6.08;8,3;8]" ..
	"listring[current_name;main]" ..
	"listring[current_player;main]" ..
	"listring[current_name;craft]" ..
	"listring[current_player;main]" ..
	"listring[current_name;armor]" ..
	"listring[current_player;main]" ..
	default.get_hotbar_bg(0,4.85)

local share_bones_time = tonumber(minetest.settings:get("share_leaveghost_time")) or 120
local share_bones_time_early = tonumber(minetest.settings:get("share_leaveghost_time_early")) or share_bones_time / 4

local data=minetest.get_mod_storage()
local function on_move(from,to)
	local off=vector.subtract(to,from)
	local meta=minetest.get_meta(to)
	local pl=meta:get_string("dropper")
	local pos=minetest.string_to_pos(data:get_string(pl.."_leaveghost_pos"))
	if not pos then return end
	pos=vector.add(pos,off)
	data:set_string(pl.."_leaveghost_pos",minetest.pos_to_string(pos))
end
local pil={}

minetest.register_node("leaveghost:bones", {
	description = S("Phantom"),
	tiles = {
		"gbones_top.png^[transform2",
		"gbones_bottom.png",
		"gbones_side.png",
		"gbones_side.png",
		"gbones_rear.png",
		"gbones_front.png"
	},
	paramtype2 = "facedir",
	groups = {not_in_creative_inventory=1},
	sounds = default.node_sound_gravel_defaults(),
	walkable=false,

	can_dig = function(pos, player)
		local inv = minetest.get_meta(pos):get_inventory()
		local name = ""
		if player then
			name = player:get_player_name()
		end
		return is_owner(pos, name) and inv:is_empty("main")
	end,

	allow_metadata_inventory_move = function(pos, from_list, from_index, to_list, to_index, count, player)
		if not pil[to_list] then return 0 end
		if is_owner(pos, player:get_player_name()) then
			return count
		end
		return 0
	end,

	allow_metadata_inventory_put = function(pos, listname, index, stack, player)
		if not pil[listname] then return 0 end
		if is_owner(pos, player:get_player_name()) then
			return stack:get_count()
		end
		return 0
	end,

	allow_metadata_inventory_take = function(pos, listname, index, stack, player)
		if is_owner(pos, player:get_player_name()) then
			return stack:get_count()
		end
		return 0
	end,

	on_metadata_inventory_take = function(pos, listname, index, stack, player)
		local meta = minetest.get_meta(pos)
		local empt=true
		local inv=meta:get_inventory()
		for k,v in pairs(bones.bones_inventory_lists) do
			empt=empt and inv:is_empty(v)
		end
		if empt then
			local inv = player:get_inventory()
			minetest.remove_node(pos)
		end
	end,

	on_punch = function(pos, node, player)
		if not is_owner(pos, player:get_player_name()) then
			return
		end

		if minetest.get_meta(pos):get_string("infotext") == "" then
			return
		end

		local inv = minetest.get_meta(pos):get_inventory()
		local player_inv = player:get_inventory()
		local has_space = true
		for _,list_name in ipairs(bones.bones_inventory_lists) do
			if inv:get_list(list_name) then
				for i = 1, inv:get_size(list_name) do
					local stk = inv:get_stack(list_name, i)
					if player_inv:room_for_item("main", stk) then
						inv:set_stack(list_name, i, nil)
						player_inv:add_item("main", stk)
					else
						has_space = false
						break
					end
				end
			end
		end

		-- remove bones if player emptied them
		if has_space then
			minetest.remove_node(pos)
		end
	end,

	on_timer = function(pos, elapsed)
		local meta = minetest.get_meta(pos)
		local time = meta:get_int("time") + elapsed
		if time >= share_bones_time then
			meta:set_string("infotext", S("@1's old phantom", meta:get_string("owner")))
			meta:set_string("owner", "")
		else
			meta:set_int("time", time)
			return true
		end
	end,
	on_blast = function(pos)
	end,
	
	on_movenode=on_move,
	mesecon={
		on_mvps_move=function(pos,node,oldpos,meta)
			on_move(oldpos,pos)
		end
	}
})

local function may_replace(pos, player)
	local node_name = minetest.get_node(pos).name
	local node_definition = minetest.registered_nodes[node_name]

	-- if the node is unknown, we return false
	if not node_definition then
		return false
	end

	-- allow replacing air
	if node_name == "air" then
		return true
	end

	-- don't replace nodes inside protections
	if minetest.is_protected(pos, player:get_player_name()) then
		return false
	end

	-- allow replacing liquids
	if node_definition.liquidtype ~= "none" then
		return true
	end

	-- don't replace filled chests and other nodes that don't allow it
	local can_dig_func = node_definition.can_dig
	if can_dig_func and not can_dig_func(pos, player) then
		return false
	end

	-- default to each nodes buildable_to; if a placed block would replace it, why shouldn't bones?
	-- flowers being squished by bones are more realistical than a squished stone, too
	return node_definition.buildable_to
end

local drop = function(pos, itemstack)
	local obj = minetest.add_item(pos, itemstack:take_item(itemstack:get_count()))
	if obj then
		obj:set_velocity({
			x = math.random(-10, 10) / 9,
			y = 5,
			z = math.random(-10, 10) / 9,
		})
	end
end

local player_inventory_lists = { "main", "craft" }
local bones_inventory_lists = (not armor) and player_inventory_lists or {"main","craft","armor"}
bones.player_inventory_lists = player_inventory_lists
bones.bones_inventory_lists=bones_inventory_lists
for k,v in pairs(player_inventory_lists) do
	pil[v]=true
end
bones.pil=pil

local function is_all_empty(player_inv,lists)
	for _, list_name in ipairs(lists or player_inventory_lists) do
		if not player_inv:is_empty(list_name) then
			return false
		end
	end
	return true
end


local function onjoin(player,_,_,_,_,pos,armorz)
	local pos=pos
	if not pos then
		pos = data:get_string(player:get_player_name().."_leaveghost_pos")
		pos=minetest.string_to_pos(pos)
		if not pos then return end
		minetest.after(0,player.set_pos,player,pos)
		pos=vector.round(pos)
	end
	local _,node,meta,inv,player_inv,drops,armor_inv,invv
	if not armorz then
		node=minetest.get_node(pos)
		if node.name=="ignore" then minetest.after(0,onjoin,player,_,_,_,_,pos) return end
		if node.name~="leaveghost:bones" then player:set_hp(0) return end
		if not is_owner(pos,player:get_player_name()) then return end

		meta=minetest.get_meta(pos)
		inv=meta:get_inventory()
		player_inv=player:get_inventory()
		data:set_string(player:get_player_name().."_leaveghost_pos","")

		drops={}

		for _, list_name in ipairs(player_inventory_lists) do
			local list=player_inv:get_list(list_name)
			if list then
				for k,v in ipairs(list) do
					if v:get_count()>0 then
						table.insert(drops,v:to_string())
					end
				end
			end
		end
	else
		node,meta,inv,player_inv,drops,armor_inv,invv=unpack(armorz)
	end

	for _, list_name in ipairs(player_inventory_lists) do
		local list=inv:get_list(list_name)
		if list then
			player_inv:set_list(list_name,list)
		end
	end
	
	if armor then
		_,armor_inv = armor:get_valid_player(player)
		if armor_inv then
			local list=armor_inv:get_list("armor")
			for i,v in ipairs(list) do
				if v:get_count()>0 then
					table.insert(drops,v:to_string())
					local vv=v:take_item(v:get_count())
					armor_inv:set_list("armor",list)
					armor:run_callbacks("on_unequip", player, i, vv)
				end
			end
		else
			minetest.handle_node_drops(pos,drops,player)
			drops={}
			if not armorz then
				invv=inv:get_list("armor")
				minetest.remove_node(pos)
			end

			minetest.after(0,function()
				onjoin(player,_,_,_,_,pos,{node,meta,inv,player_inv,drops,armor_inv,invv})
			end)
			return
		end
                armor:save_armor_inventory(player)
                armor:set_player_armor(player)
	end
	
	if armor then
		for i=1, 6 do
			local stack = invv and invv[i] or inv:get_stack("armor", i)
			if stack:get_count() > 0 then
				armor_inv:set_stack("armor", i, stack)
				armor:run_callbacks("on_equip", player, i, stack)
			end
		end
                armor:save_armor_inventory(player)
                armor:set_player_armor(player)
	end

	minetest.handle_node_drops(pos,drops,player)

	if armorz then return end

	minetest.remove_node(pos)
end

minetest.register_on_joinplayer(onjoin)


minetest.register_chatcommand("crash",{
	func=function()error()end
})

local on_leave=function(player)
	local bones_mode = minetest.settings:get("leaveghost_mode") or "bones"
	if bones_mode ~= "bones" and bones_mode ~= "drop" then
		bones_mode = "bones"
	end

	local bones_position_message = minetest.settings:get_bool("leaveghost_position_message") == true
	local player_name = player:get_player_name()
	local pos = vector.round(player:get_pos())
	local pos_string = minetest.pos_to_string(pos)
	local pos_string_real = minetest.pos_to_string(player:get_pos())

	local player_inv = player:get_inventory()
        --[[if is_all_empty(player_inv) then
		return
	end]]

        if minetest.is_creative_enabled(player_name) then
		return
	end

	do
		local mlist=player_inv:get_list("main")
		for k,v in pairs(mlist) do
			if v:get_count()>0 then
				local name=v:get_name()
				local def=minetest.registered_items
				if def and def.groups
				and def.groups.leaveghost_inhibitor
				and def.groups.leaveghost_inhibitor>0 then
					return
				end
			end
		end
	end

	-- check if it's possible to place bones, if not find space near player
	if bones_mode == "bones" and not may_replace(pos, player) then
		local air = minetest.find_node_near(pos, 1, {"air"})
		if air and not minetest.is_protected(air, player_name) then
			pos = air
			pos_string_real=minetest.pos_to_string(pos)
		else
			bones_mode = "drop"
		end
	end

	if bones_mode == "drop" then
		for _, list_name in ipairs(player_inventory_lists) do
			if player_inv:get_list(list_name) then
				for i = 1, player_inv:get_size(list_name) do
					drop(pos, player_inv:get_stack(list_name, i))
				end
				player_inv:set_list(list_name, {})
			end
		end
		if armor then
			local _,armor_inv = armor:get_valid_player(player)
			if armor_inv then
				local list=armor_inv:get_list("armor")
				for i,v in ipairs(list) do
					if v:get_count()>0 then
						drop(pos,v)
					end
					armor_inv:set_list("armor",list)
					armor:run_callbacks("on_unequip", player, i, stack)
				end
			end
			armor:save_armor_inventory(player)
			armor:set_player_armor(player)
		end
		minetest.log("action", player_name .. " leaves at " .. pos_string ..
			". Inventory dropped")
		if bones_position_message then
			minetest.chat_send_player(player_name, S("@1 left at @2, and dropped their inventory.", player_name, pos_string))
		end
		player:set_hp(0)
		return
	end

	local param2 = minetest.dir_to_facedir(player:get_look_dir())
	minetest.set_node(pos, {name = "leaveghost:bones", param2 = param2})

	minetest.log("action", player_name .. " leaves at " .. pos_string ..
		". Phantom placed")
	data:set_string(player_name.."_leaveghost_pos",pos_string_real)
	if bones_position_message then
		minetest.chat_send_player(player_name, S("@1 left at @2, and phantom was placed.", player_name, pos_string))
	end

	local player_sizes=player_inventory_lists

	local meta = minetest.get_meta(pos)
	local inv = meta:get_inventory()

	for _, list_name in ipairs(player_inventory_lists) do
		if player_inv:get_list(list_name) then
			inv:set_size(list_name, player_inv:get_size(list_name))
			inv:set_list(list_name,player_inv:get_list(list_name))
			player_inv:set_list(list_name, {})
		end
	end

	if armor then
		local _,armor_inv = armor:get_valid_player(player)
		inv:set_size("armor",6)
		if armor_inv then
			local list=armor_inv:get_list("armor")
			for i,v in ipairs(list) do
				if v:get_count()>0 then
					inv:set_stack("armor",i,v)
					v:set_count(0)
				end
				armor_inv:set_list("armor",list)
				armor:run_callbacks("on_unequip", player, i, stack)
			end
		end
                armor:save_armor_inventory(player)
                armor:set_player_armor(player)
	end

	meta:set_string("formspec", bones_formspec)
	meta:set_string("owner", player_name)
	meta:set_string("dropper",player_name)

	if share_bones_time ~= 0 then
		meta:set_string("infotext", S("@1's fresh phantom", player_name))

		if share_bones_time_early == 0 or not minetest.is_protected(pos, player_name) then
			meta:set_int("time", 0)
		else
			meta:set_int("time", (share_bones_time - share_bones_time_early))
		end

		minetest.get_node_timer(pos):start(10)
	else
		meta:set_string("infotext", S("@1's phantom", player_name))
	end
end
minetest.register_on_leaveplayer(on_leave)
minetest.register_on_shutdown(function()
	for _,v in ipairs(minetest.get_connected_players()) do
		on_leave(v)
	end
end)
