local CannibalismUtils = require("Cannibalism_Utils")

function GetARGB(color)
    return {
        a = color.a,
        r = color.r,
        g = color.g,
        b = color.b
    }
end

local fontConfig = {
    Small  = { y = 15, iconY = 2 },
    Medium = { y = 20, iconY = 4 },
    Large  = { y = 20, iconY = 6 },
}

local function injectTooltip(stats, self)
    local fontSize = getCore():getOptionTooltipFont();
    local tooltipHeight = self.tooltip:getHeight();
    local height = fontConfig[fontSize].y * (#stats + 1) - 10
    self:setY(self.tooltip:getY() + tooltipHeight);
    self:setHeight(height);
    local hDiff = self.height + 9
    local bgARGB = GetARGB(self.backgroundColor)
    local borderARGB = GetARGB(self.borderColor)
    self:drawRect(0, 0, self.width, hDiff, bgARGB.a, bgARGB.r, bgARGB.g, bgARGB.b);
    self:drawRectBorder(0, 0, self.width, hDiff, borderARGB.a, borderARGB.r, borderARGB.g, borderARGB.b);
    local x = 5
    local y = tooltipHeight + 5
    local marginCurrent = 90


    for _, statsRow in ipairs(stats) do
        local insanityLoss = statsRow[2]
        y = y + fontConfig[fontSize].y

        self.tooltip:DrawText(self.tooltip:getFont(), getText("Tooltip_Insanity_Stat") .. ": ", x, y - 15, 1, 1, 0.8, 1);
        self.tooltip:DrawText(self.tooltip:getFont(), tostring(insanityLoss),
            getTextManager():MeasureStringX(self.tooltip:getFont(), getText("Tooltip_Insanity_Stat") .. ": ") + 10,
            y - 15, 0, 1, 0, 1);
    end
end

local function injectInsanityLossStat(item, self)
    local insanityLoss = SandboxVars.Cannibalism.PointsDecrementCandy
    local stats = {
        { "Insanity", -insanityLoss },
    }

    injectTooltip(stats, self)
end

local old_ISToolTipInv_render = ISToolTipInv.render
function ISToolTipInv:render()
    if not (not ISContextMenu.instance or not ISContextMenu.instance.visibleCheck) then
        return
    end

    local item = self.item
    -- if not item:IsWeapon() then
    --     old_ISToolTipInv_render(self)
    --     return
    -- end

    if CannibalismUtils.isCandy(item) then
        injectInsanityLossStat(item, self)
    end
    old_ISToolTipInv_render(self)
end
