NHVarifeedColor = {}

function NHVarifeedColor.prerequisitesPresent(specializations)
    return SpecializationUtil.hasSpecialization(Cutter, specializations)
end

function NHVarifeedColor.registerEventListeners(vehicleType)
    SpecializationUtil.registerEventListener(vehicleType, "onPostLoad", NHVarifeedColor)
end

function NHVarifeedColor:onPostLoad(savegame)
    NHVarifeedColor.applyConfiguredColor(self)
end

function NHVarifeedColor.applyConfiguredColor(self)
    if not self.isClient then
        return
    end

    local selectedMaterial = nil
    if VehicleConfigurationItemColor ~= nil and VehicleConfigurationItemColor.getMaterialByColorConfiguration ~= nil then
        selectedMaterial = VehicleConfigurationItemColor.getMaterialByColorConfiguration(self, "baseColor")
    end

    local color = selectedMaterial ~= nil and selectedMaterial.colorScale or nil
    if color == nil then
        Logging.warning("[NH VARIFEED COLOR] Could not resolve selected base color")
        return
    end

    local applied = 0

    local function applyToNode(node)
        if node == nil or node == 0 then
            return
        end

        if getHasClassId(node, ClassIds.SHAPE) then
            local name = getName(node)

            -- In the main skinned shape, terraFlex3050_mainHeader_mat is the
            -- second material (index 1). The grain-tank extension uses it as
            -- its only material (index 0).
            if name == "terraFlex3050_41_vis" then
                setShaderParameter(node, "colorScale", color[1], color[2], color[3], 1, false, 1)
                applied = applied + 1
            elseif name == "grainExtensionPart01" then
                setShaderParameter(node, "colorScale", color[1], color[2], color[3], 1, false, 0)
                applied = applied + 1
            elseif name == "halmteiler part 1.i3d" or name == "halmteiler " or name == "halmteiler RR" then
                -- These parts use the two materials named "Default OBJ".
                -- Both materials were converted to the vehicle shader so they
                -- can use the same configured color as the main header.
                setShaderParameter(node, "colorScale", color[1], color[2], color[3], 1, false, 0)
                applied = applied + 1
            end
        end

        for i = 0, getNumOfChildren(node) - 1 do
            applyToNode(getChildAt(node, i))
        end
    end

    for _, component in ipairs(self.components or {}) do
        applyToNode(component.node)
    end

    Logging.info("[NH VARIFEED COLOR] Applied configured color to %d material(s)", applied)
end
