--[[
    =====================================================================
    Addon        : [DLTX] Activated Charcoal
    Link:        : https://www.moddb.com/mods/stalker-anomaly/addons/dltx-activated-charcoal/
    Author       : TosoxDev
    Credits      : Igigog, Arti
    Last Edit    : 09.06.2023
    =====================================================================
--]]

local cfg_ini = ini_file("items\\settings\\drug_charcoal_config.ltx")

local loot_coefficient = 1.0
local trader_restock_amount = 3.0
local safe_uninstall = false

function delete_addon_items()
    for i = 1, 65534 do
        local obj = alife_object(i)
        if obj then
            if string.match(obj:name(), "drug_charcoal") then
                alife_release(obj)
            end
        end
    end
end

function on_option_change()
    loot_coefficient = drug_charcoal_mcm.get_config("loot_coefficient")
    trader_restock_amount = drug_charcoal_mcm.get_config("trader_restock_amount")
    safe_uninstall = drug_charcoal_mcm.get_config("safe_uninstall")

    if safe_uninstall and level.present() then
        delete_addon_items()
        drug_charcoal_mcm.set_config("safe_uninstall", false)
    end
end

function actor_on_first_update()
    on_option_change()
end

local orig_trader_update = trader_autoinject.update
function trader_autoinject.update(npc)
    orig_trader_update(npc)

    local is_medic = trader_autoinject.get_trader_type(npc) == trader_autoinject.MEDIC
    if is_medic then
        trader_autoinject.spawn_items(npc, { ["drug_charcoal"] = trader_restock_amount }, true)
    end
end

local orig_spawn_cosmetics = death_manager.spawn_cosmetics
function death_manager.spawn_cosmetics(npc, npc_id, npc_comm, npc_rank, visual, rand_condition)
    orig_spawn_cosmetics(npc, npc_id, npc_comm, npc_rank, visual, rand_condition)

    local max_uses = SYS_GetParam(2, "drug_charcoal", "max_uses", 1)
    local do_uses = math.random(max_uses)
    local chance = (cfg_ini:r_float("body_loot_chance", npc_rank) or 0.05) * loot_coefficient
    if math.random() < chance then
        alife_create_item("drug_charcoal", npc, { ["uses"] = do_uses })
    end
end

function on_game_start()
    RegisterScriptCallback("on_option_change", on_option_change)
    RegisterScriptCallback("actor_on_first_update", actor_on_first_update)
end