local modpath = minetest.get_modpath("destruction_counter")

destruction_counter = {}
destruction_counter.nodesDestroyed = 0
local nodesDestroyedByHand = 0

local idText
local idMeter
minetest.register_on_joinplayer(function(player)
	meta = player:get_meta()
	

	idText = player:hud_add({
		hud_elem_type = "text",
		position      = {x = .5, y = .5},
		offset        = {x = 0,   y = 0},
		text          = nodesDestroyed,
		alignment     = {x = 0, y = 0},  -- center aligned
		scale         = {x = 100, y = 100}, -- covered later
	})
	
	player:hud_add({
		hud_elem_type = "image",
		position  = {x = 1, y = .5},
		offset    = {x = -515, y = 23},
		text      = "destruction_counter_meter_empty.png",
		scale     = {x = 4, y = 4},
		alignment = {x = 1, y = 0},
	})

	idMeter = player:hud_add({
		hud_elem_type = "image",
		position  = {x = 1, y = .5},
		offset    = {x = -510, y = 23},
		text      = "destruction_counter_meter_full.png",
		scale     = {x = 0, y = 4},
		alignment = {x = 1, y = 0},
	})
end)

minetest.register_on_dignode(function(pos, oldnode, digger)
	nodesDestroyedByHand = nodesDestroyedByHand + 1
	destruction_counter.updateCounter(digger)
end)

function destruction_counter.updateCounter(player)
	if not player then
		return
	end
	
	local totalDestruction = destruction_counter.nodesDestroyed + math.floor(nodesDestroyedByHand / 10)
	local percentage = (totalDestruction / 1000 * 4)
	if percentage > 100 then
		percentage = 100
	end
	player:hud_change(idText, "text", "Destruction meter: " .. totalDestruction)
	player:hud_change(idMeter, "scale", {x = percentage, y = 4})
end

