UytReplaceEvent = {}
local UytReplaceEvent_mt = Class(UytReplaceEvent, Event)
InitEventClass(UytReplaceEvent, "UytReplaceEvent")

function UytReplaceEvent.emptyNew()
	return Event.new(UytReplaceEvent_mt)
end

function UytReplaceEvent.new(vehicle, tyresPrice)
	local self = UytReplaceEvent.emptyNew()
	self.vehicle = vehicle
    self.tyresPrice = tyresPrice
	return self
end

function UytReplaceEvent.readStream(self, streamId, connection)
	self.vehicle = NetworkUtil.readNodeObject(streamId)
	self.tyresPrice = streamReadFloat32(streamId)

    self:run(connection)
end

function UytReplaceEvent.writeStream(self, streamId, connection)
	NetworkUtil.writeNodeObject(streamId, self.vehicle)
	streamWriteFloat32(streamId, self.tyresPrice)
end

function UytReplaceEvent.run(self, connection)
	if self.vehicle ~= nil and self.vehicle.spec_wheels ~= nil then
        
        -- Reset reported wear status to allow new notifications after replacement
        self.vehicle.uytWearReported = nil

        for _, wheel in ipairs(self.vehicle.spec_wheels.wheels) do
            -- Reset travelled distance to simulate new tyre
            wheel.uytTravelledDist = 0
            
            -- Now trigger update
            for _, visualWheel in ipairs(wheel.visualWheels) do
                for _, visualPart in ipairs(visualWheel.visualParts) do
                    if visualPart:isa(WheelVisualPartTire) and visualPart.node ~= nil and visualPart.uytEnabled ~= nil then
                        UseYourTyres.updateWheelRadius(visualPart, false, self.vehicle)
                    end
                end
            end
        end

        if self.vehicle.isServer then
            g_currentMission:addMoney(-self.tyresPrice, self.vehicle:getOwnerFarmId(), MoneyType.VEHICLE_REPAIR, true, true)
        end
		
		if not connection:getIsServer() then
			g_server:broadcastEvent(self)
		end
	end
end
