sparktech.tool_energy_hud = {}

minetest.register_on_joinplayer(function(player)
  local idx = player:hud_add({
    hud_elem_type = "statbar",
    position = {x = 0.85, y = 0.95},
    offset = {x =-100, y = -40},
    text = "bar_red.png",
    direction = 0,
    number = 20,
    size = { x=2, y=20 }
  })
  local idy = player:hud_add({
    hud_elem_type = "text",
    position = {x = 0.85, y = 0.95},
    offset = {x = 0, y = -50},
    text = "",
    direction = 0,
    number = tonumber ("0xFFFFFF", 16)
  })
  sparktech.tool_energy_hud[player:get_player_name()] = {idb = idx, idt = idy}
end)

minetest.register_globalstep(function(dtime)
  for k, i in pairs(sparktech.tool_energy_hud) do
    local player = minetest.get_player_by_name(k)
	if player == nil then
		sparktech.tool_energy_hud[k] = nil
		return
	end
    local item = player:get_wielded_item()
    local energy = tonumber(item:get_metadata())
    local energymax = minetest.get_item_group(item:get_name(), "sparktech_energy_max")
    if energy == nil then
      energy = 0
    end
    player:hud_change(i["idb"], "number", energy / energymax * 400)
    if energymax == 0 then
      player:hud_change(i["idt"], "text", "")
    else
      player:hud_change(i["idt"], "text", energy .. " / " .. energymax)
    end
  end
end)
