local modname = minetest.get_current_modname()
local S = minetest.get_translator(modname)

_G[modname] = {}

local formspec =
{
	"formspec_version[2]",
	"size[10,9]",
	"list[current_player;main;0.1,4.1;8,4]",
	"list[context;main;2.6,0.4;4,3]",
	"listring[]",
	"label[2.6,0.25;" .. S("Barrel") .. "]",
	"label[0.1,3.9;" .. S("Inventory") .. "]",
}
formspec = table.concat(formspec)

local on_construct = function(pos)
	local meta = minetest.get_meta(pos)
	local inv = meta:get_inventory()
	inv:set_size("main", 12)
	meta:set_string("formspec", formspec)
end
local bounding_box =
{
	type =  "fixed",
	fixed = {-0.375, -0.5, -0.375, 0.375, 0.5, 0.375},
}


minetest.register_node(modname .. ":barrel",
	{
		drawtype = "mesh",
		mesh = "eg_storage_barrels_barrel.obj",
		tiles = {"eg_storage_barrels_wood.png", "eg_storage_barrels_rings.png", "eg_storage_barrels_top_bottom.png"},
		groups = {deconstructable = 3},
		selection_box = bounding_box,
		collision_box = bounding_box,
		on_construct = on_construct,
		sounds =
		{
			dig = "wood_high_dig",
			dug = "wood_low_dug",
			place = "wood_low_place",
			footstep = "wood_low_footstep",
		},
		can_dig = function(pos)
			local inv = minetest.get_inventory({type = "node", pos = pos})
			return inv:is_empty("main")
		end,
	})

if minetest.get_modpath("eg_dungeons") and minetest.get_modpath("inventory_populator")
then
	local dungeon_loot =
	{
		rolls = 3,
		rolls_max = 5,
		loots =
		{
			{
				weight = 5,
				loot = modname .. ":barrel",
				repetitions = 1,
				repetitions_max = 5,
			},
			accumulated_weight = 5,
		}
	}
	
	_G[modname].set_dungeon_loot_table = function(tab)
		dungeon_loot = tab
	end
	
	local get_inv_list = inventory_populator.get_inv_list
	local function populate_inv(pos, rand)
		local meta = minetest.get_meta(pos)
		local inv = meta:get_inventory()
		inv:set_list("main", get_inv_list(inv:get_size("main"), dungeon_loot, rand))
	end
	local on_construct = minetest.registered_nodes["eg_storage_barrels:barrel"].on_construct
	eg_dungeons.register_dungeon_populator(10, function(pos, rand)
			minetest.set_node(pos, {name = "eg_storage_barrels:barrel"})
			on_construct(pos)
			populate_inv(pos, rand)
		end)
end
