PyuTest.MAGIC_MANA_MAX = 150

local storage = core.get_mod_storage()
local manas = core.deserialize(storage:get("player_manas")) or {}

PyuTest.get_mana = function (player)
	return manas[player]
end

PyuTest.use_mana = function(player, amount)
	if core.is_creative_enabled(player) then
		return true
	end

	if PyuTest.get_mana(player) >= amount then
		manas[player] = manas[player] - amount
		return true
	end

	core.chat_send_player(player, string.format("Not enough mana! (Need %d)", amount))

	local obj = core.get_player_by_name(player)
	PyuTest.deal_damage(obj, obj:get_hp() / 3, PyuTest.DAMAGE_TYPES.magic())
	core.sound_play("pyutest_magic_negative", {
		gain = 1,
		player = player,
	})

	return false
end

local timers = {}
core.register_globalstep(function (dtime)
	for i, p in pairs(core.get_connected_players()) do
		local name = p:get_player_name()

		if timers[name] == nil then
			timers[name] = 0
		end

		timers[name] = timers[name] + (10 * dtime)

		if timers[name] > 1.5 then
			manas[name] = manas[name] + 1
			timers[name] = 0
		end


		if manas[name] > PyuTest.MAGIC_MANA_MAX then
			manas[name] = PyuTest.MAGIC_MANA_MAX
		end

		hb.change_hudbar(p, "mana", manas[name], PyuTest.MAGIC_MANA_MAX)
	end
end)

core.register_on_joinplayer(function(player)
	local name = player:get_player_name()
	if manas[name] == nil then
		manas[name] = PyuTest.MAGIC_MANA_MAX
	end

	hb.init_hudbar(player, "mana", manas[name], PyuTest.MAGIC_MANA_MAX)
end)

local function save_data()
	storage:set_string("player_manas", core.serialize(manas))
end

core.register_on_shutdown(save_data)
PyuTest.register_interval(save_data, 10)

hb.register_hudbar("mana", 0xFFFFFF, Translate("Mana"), {
	icon = "pyutest-mana.png",
	bar = "pyutest-mana-bg.png",
	bgicon = "pyutest-mana-bg.png"
}, 0, PyuTest.MAGIC_MANA_MAX, false)
