
FieldGroundWheelRadiusSyncEvent = {}
local FieldGroundWheelRadiusSyncEvent_mt = Class(FieldGroundWheelRadiusSyncEvent, Event)

InitEventClass(FieldGroundWheelRadiusSyncEvent, "FieldGroundWheelRadiusSyncEvent")

function FieldGroundWheelRadiusSyncEvent.emptyNew()
	return Event.new(FieldGroundWheelRadiusSyncEvent_mt)
end

function FieldGroundWheelRadiusSyncEvent.new(vehicle, radii)
	local self = FieldGroundWheelRadiusSyncEvent.emptyNew()
	self.vehicle = vehicle
	self.radii = radii or {}
	return self
end

function FieldGroundWheelRadiusSyncEvent:writeStream(streamId, connection)
	NetworkUtil.writeNodeObject(streamId, self.vehicle)

	local wheels = (self.vehicle ~= nil and self.vehicle.spec_wheels ~= nil and self.vehicle.spec_wheels.wheels) or nil
	local numWheels = (wheels ~= nil) and #wheels or 0
	streamWriteUInt8(streamId, numWheels)

	for i = 1, numWheels do
		local r = self.radii[i]
		local has = (type(r) == "number" and r == r and r > 0.01)
		streamWriteBool(streamId, has)
		if has then
			streamWriteFloat32(streamId, r)
		end
	end
end

function FieldGroundWheelRadiusSyncEvent:readStream(streamId, connection)
	self.vehicle = NetworkUtil.readNodeObject(streamId)

	local numWheels = streamReadUInt8(streamId)
	self.radii = {}

	for i = 1, numWheels do
		local has = streamReadBool(streamId)
		if has then
			self.radii[i] = streamReadFloat32(streamId)
		else
			self.radii[i] = nil
		end
	end

	self:run(connection)
end

function FieldGroundWheelRadiusSyncEvent:run(connection)
	if self.vehicle == nil or self.vehicle.spec_wheels == nil or self.vehicle.spec_wheels.wheels == nil then
		return
	end

	if g_server ~= nil then
		return
	end

	local wheels = self.vehicle.spec_wheels.wheels
	local now = g_time or 0

	local isLocalMaster = false
	if self.vehicle.getIsControlled ~= nil then
		isLocalMaster = self.vehicle:getIsControlled()
	elseif self.vehicle.getIsEntered ~= nil then
		isLocalMaster = self.vehicle:getIsEntered()
	end

	for i = 1, math.min(#wheels, #self.radii) do
		local w = wheels[i]
		local wp = (w ~= nil) and w.physics or nil
		if wp ~= nil then
			wp.__fgNetDesiredRadius = self.radii[i]
			wp.__fgNetDesiredRadiusTs = now

			if isLocalMaster then
				wp.__fgDesiredRadius = self.radii[i]

				if _G.__MudRadiusCombiner ~= nil and _G.__MudRadiusCombiner.apply ~= nil then
					_G.__MudRadiusCombiner.apply(wp, 0.0015)
				end
			end
		end
	end
end

