-- Wooden_Bucket init.lua
-- Copyright Duane Robertson (duane@duanerobertson.com), 2017, 2019
-- Distributed under the LGPLv2.1 (https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html)


local function check_protection(pos, name, text)
	if minetest.is_protected(pos, name) then
		minetest.log("action", (name ~= "" and name or "A mod")
			.. " tried to " .. text
			.. " at protected position "
			.. minetest.pos_to_string(pos)
			.. " with a bucket")
		minetest.record_protection_violation(pos, name)
		return true
	end
	return false
end

local function log_action(pos, name, action)
	minetest.log("action", (name ~= "" and name or "A mod")
		.. " " .. action .. " at " .. minetest.pos_to_string(pos) .. " with a wooden bucket")
end

local function register_liquid_wood(source, itemname, inventory_image, name, groups)
	if not (source and itemname and inventory_image and name and type(source) == 'string' and type(itemname) == 'string'
	and type(inventory_image) == 'string') then
		return
	end

	inventory_image = inventory_image..'^wooden_bucket_overlay.png'
	minetest.register_craftitem(itemname, {
		description = name,
		inventory_image = inventory_image,
		stack_max = 1,
		liquids_pointable = true,
		groups = groups,

		on_place = function(itemstack, user, pointed_thing)
			if not (user and pointed_thing) then
				return
			end

			-- Must be pointing to node
			if pointed_thing.type ~= "node" then
				return
			end

			local node = minetest.get_node_or_nil(pointed_thing.under)
			local ndef = node and minetest.registered_nodes[node.name]

			-- Call on_rightclick if the pointed node defines it
			if ndef and ndef.on_rightclick and
				user and not user:get_player_control().sneak then
				return ndef.on_rightclick(pointed_thing.under, node, user, itemstack)
			end

			local lpos

			-- Check if pointing to a buildable node
			if ndef and ndef.buildable_to then
				-- buildable; replace the node
				lpos = pointed_thing.under
			else
				-- not buildable to; place the liquid above
				-- check if the node above can be replaced
				lpos = pointed_thing.above
				local nnode = minetest.get_node_or_nil(lpos)
				if not nnode then
					return
				end

				local above_ndef = nnode and minetest.registered_nodes[nnode.name]

				if not above_ndef or not above_ndef.buildable_to then
					-- do not remove the bucket with the liquid
					return itemstack
				end
			end

			local pname = user and user:get_player_name() or ""
			if check_protection(lpos, pname, "place "..source) then
				return
			end

			minetest.set_node(lpos, {name = source})
			log_action(lpos, pname, "placed " .. source)
			return ItemStack("wooden_bucket:bucket_wood_empty")
		end
	})
end

for fluid, def in pairs(bucket.liquids) do
	if not fluid:find('flowing') and not fluid:find('lava') and not fluid:find('molten') and not fluid:find('weightless') then
		local item_name = def.itemname:gsub('[^:]+:bucket', 'wooden_bucket:bucket_wood')
		local original = minetest.registered_items[def.itemname]
		if original and item_name and item_name ~= def.itemname then
			local new_name = original.description:gsub('Bucket', 'Wooden Bucket')
			local new_image = original.inventory_image
			register_liquid_wood(fluid, item_name, new_image, new_name, original.groups)
		end
	end
end

if minetest.get_modpath("thirsty") then
	minetest.register_craft({
		output = 'wooden_bucket:bucket_wood_empty 1',
		recipe = {
			{'thirsty:wooden_bowl', '', 'thirsty:wooden_bowl'},
			{'', 'thirsty:wooden_bowl', ''},
		}
	})
else
	local res = minetest.get_craft_result({
		method = 'normal',
		width = 3,
		items = {'group:wood', '', 'group:wood','', 'group:wood', '','', '', ''},
	})

	if res and type(res.item) == 'string' then
		minetest.register_craft({
			output = 'wooden_bucket:bucket_wood_empty 1',
			recipe = {
				{'group:wood', 'group:leaves', 'group:wood'},
				{'', 'group:wood', ''},
			}
		})
	else
		minetest.register_craft({
			output = 'wooden_bucket:bucket_wood_empty 1',
			recipe = {
				{'group:wood', '', 'group:wood'},
				{'', 'group:wood', ''},
			}
		})
	end
end

minetest.register_craftitem("wooden_bucket:bucket_wood_empty", {
	description = "Empty Wooden Bucket",
	inventory_image = "wooden_bucket.png",
	groups = {tool = 1, bucket_empty = 1},
	stack_max = 99,
	liquids_pointable = true,
	on_use = function(itemstack, user, pointed_thing)
		if pointed_thing.type == "object" then
			pointed_thing.ref:punch(user, 1.0, { full_punch_interval=1.0 }, nil)
			return user:get_wielded_item()
		elseif pointed_thing.type ~= "node" then
			-- do nothing if it's neither object nor node
			return
		end
		-- Check if pointing to a liquid source
		local pos = pointed_thing.under
		local node = minetest.get_node(pos)
		local liquiddef = bucket.liquids[node.name]
		local item_count = user:get_wielded_item():get_count()

		if liquiddef ~= nil
		and liquiddef.itemname ~= nil
		and node.name == liquiddef.source then
			local pname = user:get_player_name()
			if check_protection(pos, pname, "take ".. node.name) then
				return
			end

			-- default set to return filled bucket
			local giving_back = liquiddef.itemname:gsub('^[^:]+:bucket', 'wooden_bucket:bucket_wood')

			-- check if holding more than 1 empty bucket
			if item_count > 1 then

				-- if space in inventory add filled bucked, otherwise drop as item
				local inv = user:get_inventory()
				if inv:room_for_item("main", {name=giving_back}) then
					inv:add_item("main", giving_back)
				else
					local upos = user:get_pos()
					upos.y = math.floor(upos.y + 0.5)
					minetest.add_item(upos, liquiddef.itemname)
				end

				-- set to return empty buckets minus 1
				giving_back = "wooden_bucket:bucket_wood_empty "..tostring(item_count-1)

			end

			-- force_renew requires a source neighbour
			local source_neighbor = false
			if liquiddef.force_renew then
				source_neighbor =
					minetest.find_node_near(pos, 1, liquiddef.source)
			end
			if source_neighbor and liquiddef.force_renew then
				log_action(pos, pname, "picked up " .. liquiddef.source .. " (force renewed)")
			else
				minetest.add_node(pos, {name = "air"})
				log_action(pos, pname, "picked up " .. liquiddef.source)
			end

			return ItemStack(giving_back)
		else
			-- non-liquid nodes will have their on_punch triggered
			local node_def = minetest.registered_nodes[node.name]
			if node_def then
				node_def.on_punch(pos, node, user, pointed_thing)
			end
			return user:get_wielded_item()
		end
	end,
})
