local mod_name = minetest.get_current_modname()
local mod_path = minetest.get_modpath(mod_name)
local S = minetest.get_translator(mod_name)


pmb_hud = {}

local pl = {}

local function check_player(player)
    if not pl[player] then
        pl[player] = {
            id={},
        }
    end
end

local default = {
    hotbar_bg = {
        hud_elem_type = "image",
        alignment = {x=0, y=1},
        position = {x=0.5, y=1},
        name = "health_bg",
        text = "pmb_hotbar_bg.png",
        z_index = 10,
        scale = {x = 1, y = 1},
        offset = {x = 0, y = -91},
    }
}

local _builtin = {
    health = {
        _flagname = "healthbar",
        hud_elem_type = "statbar",
        position = {x=0.5, y=1},
        name = "health",
        text = "pmb_health_full.png",
        text2 = "pmb_health_empty.png",
        z_index = 11,
        number = 13,
        item = 20,
        size = {x = 24, y = 24},
        direction = 1,
        offset = {x = -18 - 30 - 8, y = -93}
    },
    breath = {
        _flagname = "breathbar",
        hud_elem_type = "statbar",
        position = {x=0.5, y=1},
        name = "breath",
        text = "pmb_breath_full.png",
        text2 = "pmb_breath_empty.png",
        z_index = 11,
        number = 13,
        item = 20,
        size = {x = 24, y = 24},
        -- direction = 1,
        offset = {x = 18 + 30 - 16, y = -93},
    },
}

function pmb_hud.change_hud(player, tag, def)
    check_player(player)
    if pl[player].id[tag] then
        for stat, value in pairs(def) do
            player:hud_change(pl[player].id[tag], stat, value)
        end
        return
    end
end

function pmb_hud.add_hud(player, tag, def)
    check_player(player)
    if pl[player].id[tag] then
        pmb_hud.remove_hud(player, tag)
    end

    pl[player].id[tag] = player:hud_add(def)
end

function pmb_hud.remove_hud(player, tag)
    check_player(player)
    if _builtin[tag] then
        player:hud_set_flags({
            [_builtin[tag]._flagname] = false,
        })
        return
    end

    if pl[player].id[tag] then
        player:hud_remove(pl[player].id[tag])
        pl[player].id[tag] = nil
        return
    end
end

function pmb_hud.reset_hud(player, tag)
    check_player(player)
    if default[tag] then
        if not pl[player].id[tag] then
            pmb_hud.add_hud(player, tag, default[tag])
            return
        end
    end

    if _builtin[tag] then
        player:hud_set_flags({
            [_builtin[tag]._flagname] = true,
        })
        return
    end

    if pl[player].id[tag] then
        pmb_hud.remove_hud(player, tag)
        return
    end
end


minetest.hud_replace_builtin("health", _builtin.health)

minetest.hud_replace_builtin("breath", _builtin.breath)

minetest.register_on_joinplayer(function(player)
    check_player(player)
    player:hud_set_flags({
        minimap_radar = false,
    })
    pl[player].id.hotbar_bg = player:hud_add(default.hotbar_bg)
end)
