-- LUALOCALS < ---------------------------------------------------------
local minetest, pairs, piredo_api, piredo_player, vector
    = minetest, pairs, piredo_api, piredo_player, vector
-- LUALOCALS > ---------------------------------------------------------

local api = piredo_api.get_mod_api()
local modname = minetest.get_current_modname()

do
	local halfnode = vector.new(0.5, 0.5, 0.5)
	api.digparticles = function(pos, node)
		return minetest.add_particlespawner({
				amount = 50,
				time = 0.01,
				pos = {
					min = vector.subtract(pos, halfnode),
					max = vector.add(pos, halfnode),
				},
				node = node,
				acc = vector.new(0, -10, 0),
				vel = {
					min = vector.new(1, 1, 1),
					max = vector.new(-1, -1, -1)
				},
				collisiondetection = true,
				exptime = {min = 1, max = 2, bias = 1},
				size = {min = 0.5, max = 2}
			})
	end
end

api.digsound = function(pos, node)
	local def = minetest.registered_items[node.name]
	local spec = def and def.sounds and (def.sounds.dug
		or def.sounds.dig)
	if spec then
		local param = {}
		for k, v in pairs(spec) do param[k] = v end
		param.pos = pos
		minetest.sound_play(param.name, param, true)
	end
end

api.digeffect = function(pos, node)
	api.digsound(pos, node)
	return api.digparticles(pos, node)
end

minetest.register_entity(modname .. ":pickup", {
		initial_properties = {static_save = false}
	})

api.pickupeffect = function(pos, node)
	api.digsound(pos, node)
	local def = minetest.registered_items[node.name]
	if not def then return api.digparticles(pos, node) end
	local obj = minetest.add_entity(pos, modname .. ":pickup")
	local props = def.inventory_image and def.inventory_image ~= "" and {
		visual = "sprite",
		textures = {def.inventory_image},
		} or {
		visual = "wielditem",
		textures = {node.name},
	}
	props.visual_size = {x = 0.5, y = 0.5}
	props.is_visible = true
	props.physical = false
	props.pointable = false
	obj:set_properties(props)
	minetest.after(0, function()
			minetest.after(0, function()
					local player = piredo_player:mainplayer()
					if player then
						obj:move_to(vector.offset(player:get_pos(), 0, 1, 0))
					end
					minetest.after(0.25, function() obj:remove() end)
				end)
		end)
end
