PyuTest.HUNGER_MAX = 20
PyuTest.HUNGER_RUNOUT = 200

local storage = core.get_mod_storage()
local hungers = core.deserialize(storage:get("player_hungers")) or {}

PyuTest.hunger_multiplier = function(player, x)
	hungers[player].multiplier = x
end

PyuTest.hunger_get = function (player)
	return hungers[player].hunger
end

PyuTest.hunger_set = function (player, hunger)
	hungers[player].hunger = hunger
end

PyuTest.hunger_add = function (player, points)
	if hungers[player].hunger == PyuTest.HUNGER_MAX and points >= 0 then
		return
	end

	if hungers[player].hunger <= 0 and points < 0 then
		return
	end

	local p = hungers[player].hunger + points
	if p > PyuTest.HUNGER_MAX then
		p = PyuTest.HUNGER_MAX
	end

	hungers[player].hunger = p
end

core.register_on_joinplayer(function(player)
	local name = player:get_player_name()
	if hungers[name] == nil then
		hungers[name] = {
			hunger = PyuTest.HUNGER_MAX,
			multiplier = 1
		}
	end

	if core.settings:get_bool("enable_damage", true) then
		hb.init_hudbar(player, "hunger", hungers[name].hunger, PyuTest.HUNGER_MAX)
	end
end)

core.register_on_respawnplayer(function (player)
	local name = player:get_player_name()
	hungers[name].hunger = PyuTest.HUNGER_MAX
end)

local function save_data()
	storage:set_string("player_hungers", core.serialize(hungers))
end

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

if not core.settings:get_bool("enable_damage", true) then
	return
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 hungers[name].hunger < 0 then
			hungers[name].hunger = 0
		end

		if timers[name] == nil then
			timers[name] = {
				hunger = 0,
				damage = 0,
				health = 0,
			}
		end

		timers[name].hunger = timers[name].hunger + ((3 * hungers[name].multiplier) * dtime)
		timers[name].damage = timers[name].damage + 5 * dtime
		timers[name].health = timers[name].health + 8 * dtime

		if timers[name].hunger > PyuTest.HUNGER_RUNOUT then
			PyuTest.hunger_add(name, -2)
			timers[name].hunger = 0
		end

		if timers[name].damage > 20 and hungers[name].hunger == 0 then
			PyuTest.deal_damage(p, 3, PyuTest.DAMAGE_TYPES.starvation())
			timers[name].damage = 0
		end

		if timers[name].health > 10 and hungers[name].hunger == 20 then
			PyuTest.deal_damage(p, -2)
			timers[name].health = 0
		end

		hb.change_hudbar(p, "hunger", hungers[name].hunger, PyuTest.HUNGER_MAX)
	end
end)

hb.register_hudbar("hunger", 0xFFFFFF, Translate("Hunger"), {
	icon = "pyutest-hunger.png",
	bar = "pyutest-hunger-bg.png",
	bgicon = "pyutest-hunger-bg.png"
}, 0, PyuTest.HUNGER_MAX, false)
