local hud
local hpBar
local manaBar
local levelLabel
local hpLabel
local manaLabel

local function updateBar(bar, label, current, maximum)
  if not bar or not label then return end
  current = tonumber(current) or 0
  maximum = tonumber(maximum) or 0

  if maximum > 0 then
    bar:setPercent(math.max(0, math.min(100, current * 100 / maximum)))
  else
    bar:setPercent(0)
  end

  label:setText(string.format('%d / %d', current, maximum))
end

function init()
  connect(g_game, {
    onGameStart = show,
    onGameEnd = hide,
    onHealthChange = updateHealth,
    onManaChange = updateMana
  })

  hud = g_ui.loadUI('game_hud.otui', modules.game_interface.getRootPanel())
  if hud then
    hpBar = hud:recursiveGetChildById('hpBar')
    manaBar = hud:recursiveGetChildById('manaBar')
    hpLabel = hud:recursiveGetChildById('hpLabel')
    manaLabel = hud:recursiveGetChildById('manaLabel')
    levelLabel = hud:recursiveGetChildById('levelLabel')
  end

  if g_game.isOnline() then
    show()
  else
    hide()
  end
end

function terminate()
  disconnect(g_game, {
    onGameStart = show,
    onGameEnd = hide,
    onHealthChange = updateHealth,
    onManaChange = updateMana
  })

  hpBar = nil
  manaBar = nil
  hpLabel = nil
  manaLabel = nil
  levelLabel = nil

  if hud then
    hud:destroy()
    hud = nil
  end
end

function show()
  if not hud then return end
  hud:show()
  update()
end

function hide()
  if hud then hud:hide() end
end

function updateHealth()
  local player = g_game.getLocalPlayer()
  if not player then return end
  updateBar(hpBar, hpLabel, player:getHealth(), player:getMaxHealth())
end

function updateMana()
  local player = g_game.getLocalPlayer()
  if not player then return end
  updateBar(manaBar, manaLabel, player:getMana(), player:getMaxMana())
end

function update()
  local player = g_game.getLocalPlayer()
  if not player then return end

  updateHealth()
  updateMana()

  if levelLabel then
    levelLabel:setText('Level ' .. tostring(player:getLevel()))
  end
end
