TirePressureVehicleActionRegister = TirePressureVehicleActionRegister or {}
TirePressureVehicleActionRegister.modName = g_currentModName or "FS25_MudSystemPhysics"
TirePressureVehicleActionRegister.modDirectory = g_currentModDirectory or ""
TirePressureVehicleActionRegister._didRegister = TirePressureVehicleActionRegister._didRegister or false

local SPEC_SHORT_NAME = "mudsysTirePressureAction"
local SPEC_CLASS = "TirePressureVehicleAction"

local function hasSpecializationByObject(specs, specialization)
    return specs ~= nil
        and specialization ~= nil
        and SpecializationUtil ~= nil
        and SpecializationUtil.hasSpecialization ~= nil
        and SpecializationUtil.hasSpecialization(specialization, specs)
end

function TirePressureVehicleActionRegister.register()
    if TirePressureVehicleActionRegister._didRegister == true then
        return
    end

    if g_specializationManager == nil or g_vehicleTypeManager == nil or g_vehicleTypeManager.types == nil then
        return
    end

    TirePressureVehicleActionRegister._didRegister = true

    local fullName = TirePressureVehicleActionRegister.modName .. "." .. SPEC_SHORT_NAME
    local specFile = Utils.getFilename("scripts/TirePressureVehicleAction.lua", TirePressureVehicleActionRegister.modDirectory)

    if g_specializationManager.getSpecializationByName == nil
        or g_specializationManager:getSpecializationByName(fullName) == nil then
        g_specializationManager:addSpecialization(fullName, SPEC_CLASS, specFile, nil)
    end

    local added = 0
    for typeName, vehicleType in pairs(g_vehicleTypeManager.types) do
        local specs = vehicleType ~= nil and vehicleType.specializations or nil
        local specsByName = vehicleType ~= nil and vehicleType.specializationsByName or nil

        local hasWheels = (specsByName ~= nil and specsByName["wheels"] ~= nil)
            or hasSpecializationByObject(specs, Wheels)

        local hasAlready = (specsByName ~= nil and (specsByName[fullName] ~= nil or specsByName[SPEC_SHORT_NAME] ~= nil))
            or hasSpecializationByObject(specs, TirePressureVehicleAction)

        if hasWheels and not hasAlready then
            g_vehicleTypeManager:addSpecialization(typeName, fullName)
            added = added + 1
        end
    end

    print(string.format("[MudSystemPhysics] Tire pressure specialization injected into %d wheeled vehicle types", added))
end

if TypeManager ~= nil and TypeManager.validateTypes ~= nil and Utils ~= nil and Utils.prependedFunction ~= nil then
    TypeManager.validateTypes = Utils.prependedFunction(TypeManager.validateTypes, TirePressureVehicleActionRegister.register)
else
    TirePressureVehicleActionRegister.register()
end
