
local function update_hud(object, meta)
    meta.n = (meta.n or 0) + 1
    local opacity = 1
    -- minetest.log(dump(meta))

    if not meta.total_time then meta.total_time = 0 end
    if meta.total_time < (meta.blend_in or 2) then
        opacity = meta.total_time / (meta.blend_in or 2)
    elseif meta.time < (meta.blend_out or 2) then
        opacity = meta.time / (meta.blend_out or 2)
    end

    -- tilt it toward a more quadratic kind of slope
    opacity = (1 - opacity) * opacity + opacity
    local base_opacity = 255
    pmb_hud.change_hud(object, "pmb_status_blindness", {
        text = "(pmb_status_blindness_bg.png^[opacity:250)"..
        "^(pmb_status_blindness_noise_"..tostring(meta.n % 3 + 1)..".png^[opacity:50)^[opacity:"..tostring(base_opacity * opacity)
    })
end

local function add_hud(object, meta)
    pmb_hud.add_hud(object, "pmb_status_blindness", {
        hud_elem_type = "image",
        type = "image",
        scale = {x=-100, y=-100},
        text = "blank.png",
        position = {x=0.5, y=0.5},
        offset = {x=0, y=0},
        z_index = 19
    })
    -- update_hud(object, meta)
end

pmb_statusfx.register_status("blindness", {
    ----
    fx_allow_player = true,
    -- fx_allow_object = true,
    -- if true, counts down one stack then the next, rather than all of them, allows stacking time up infinitely
    fx_only_tick_once = false,
    fx_only_apply_once = false,
    fx_timeout_individual = false,
    -- fx_use_player_functions_for_objects = true,
    ----
    on_apply_player = function(object, count, meta, params)
        meta.update_time = 0.1
        meta.blend_in = params.blend_in or 2
        meta.blend_out = params.blend_out or 2
        if count == 1 then add_hud(object, meta) end
        return false -- true to prevent apply
    end,
    on_remove_player = function(object, count, meta, not_timeout)
        pmb_hud.remove_hud(object, "pmb_status_blindness")
        return false -- true to prevent remove
    end,
    on_step_player = function(object, count, meta, dtime)
        meta.total_time = (meta.total_time or 0) + dtime
        meta.update_time = (meta.update_time or 0.5) - dtime
        meta._count = count
        if meta.update_time <= 0 then
            meta.update_time = meta.update_time + 0.1
        else
            return false
        end
        update_hud(object, meta)
        return false -- true to remove
    end,
    ----
    hud = pmb_statusfx.hud.make_effect("pmb_status_blind.png")
    ----
})

