CannibalismParamEditor = CannibalismParamEditor or {}
local CannibalismUtils = {}

local function initializeReqs()
    CannibalismUtils = require("Cannibalism_Utils")
end

Events.OnInitGlobalModData.Add(initializeReqs)

local function getCandyItems()
    local items = SandboxVars.Cannibalism.CandyItems or ""
    local itemsToEdit = {}
    for item in string.gmatch(items, '([^;]+)') do
        table.insert(itemsToEdit, item)
    end
    return itemsToEdit
end

function CannibalismParamEditor.reducePoints(item, character, amount)
    if amount == 1 then
        local vars = SandboxVars.Cannibalism
        local currentPoints = CannibalismUtils.getPlayerInsanityPoints(character)

        local newPoints = currentPoints - vars.PointsDecrementCandy
        if newPoints < 0 then newPoints = 0 end
        character:getModData().Cannibalism_InsanityPoints = newPoints

        local insanityStage = CannibalismUtils.getPlayerInsanityStage(character)

        if MF then
            MF.getMoodle("insane", character:getPlayerNum()):setValue(insanityStage) --float
        end
    end
end

local function EditParams()
    local scriptManager = getScriptManager()
    local itemsToEdit = getCandyItems()

    if itemsToEdit then
        for _, item in ipairs(itemsToEdit) do
            scriptManager:getItem(item):DoParam("OnEat = CannibalismParamEditor.reducePoints")
        end
    end

    local isZombieMeatPoisonous = SandboxVars.Cannibalism.PoisonousZombieMeat
    local zombieMeat = scriptManager:getItem("ZombieMeat")

    if zombieMeat then
        if not isZombieMeatPoisonous then
            zombieMeat:DoParam("Poison = false")
            zombieMeat:DoParam("Tooltip = Tooltip_item_ZombieMeatNoPoison")
            zombieMeat:DoParam("PoisonPower = 0")
        else
            local poisonPower = SandboxVars.Cannibalism.ZombieMeatPoisonPower
            zombieMeat:DoParam("Poison = true")
            zombieMeat:DoParam("Tooltip = Tooltip_item_ZombieMeatPoison")
            zombieMeat:DoParam("PoisonPower = " .. tostring(poisonPower))
        end
    end
end

Events.OnInitGlobalModData.Add(EditParams)
