
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
    aom_hud.change_hud(object, "aom_status_blindness", {
        text = "(aom_status_blindness_bg.png^[opacity:250)"..
        "^(aom_status_blindness_noise_"..tostring(meta.n % 3 + 1)..".png^[opacity:50)^[opacity:"..tostring(math.ceil(opacity*20) * 255 / 20)
    })
end

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

aom_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 or params.is_reapply then
            add_hud(object, meta) end
        return false -- true to prevent apply
    end,
    on_remove_player = function(object, count, meta, not_timeout)
        aom_hud.remove_hud(object, "aom_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 = aom_statusfx.hud.make_effect("aom_status_blind.png")
    ----
})

