--[[
    TogglePTOAttachStateEvent

    Multiplayer Sync Event for PTO attachments

	@author: 		BayernGamers
	@date: 			06.06.2025
	@version:		1.0

	History:		v1.0 @06.06.2025 - initial implementation in FS25
                    ------------------------------------------------------------------------------------------------------
	
	License:        Terms:
                        Usage:
                            Feel free to use this work as-is as long as you adhere to the following terms:
						Attribution:
							You must give appropriate credit to the original author when using this work.
						No Derivatives:
							You may not alter, transform, or build upon this work in any way.
						Usage: 
							The work may be used for personal and commercial purposes, provided it is not modified or adapted.
						Additional Clause:
							This script may not be converted, adapted, or incorporated into any other game versions or platforms except by GIANTS Software.
]]
TogglePTOAttachStateEvent = {}

local TogglePTOAttachStateEvent_mt = Class(TogglePTOAttachStateEvent, Event)

InitEventClass(TogglePTOAttachStateEvent, "TogglePTOAttachStateEvent")

function TogglePTOAttachStateEvent:emptyNew()
    local self = Event.new(TogglePTOAttachStateEvent_mt)
    return self
end

function TogglePTOAttachStateEvent.new(vehicle, attachedVehicle)
    local self = TogglePTOAttachStateEvent:emptyNew()
    self.vehicle = vehicle
    self.attachedVehicle = attachedVehicle

    return self
end

function TogglePTOAttachStateEvent:writeStream(streamId, connection)
    NetworkUtil.writeNodeObject(streamId, self.vehicle)
    NetworkUtil.writeNodeObject(streamId, self.attachedVehicle)
end

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

    self:run(connection)
end

function TogglePTOAttachStateEvent:run(connection)
    if not connection:getIsServer() then
        g_server:broadcastEvent(self, false, nil, self.vehicle)
    end
    if self.vehicle ~= nil and self.attachedVehicle ~= nil then
        self.vehicle:togglePTOAttachState(self.attachedVehicle)
    end
end

function TogglePTOAttachStateEvent.sendEvent(vehicle, attachedVehicle, noEventSend)
    if noEventSend == nil or noEventSend == false then
        if g_server ~= nil then
            g_server:broadcastEvent(TogglePTOAttachStateEvent.new(vehicle, attachedVehicle), nil, nil, vehicle)
        else
            g_client:getServerConnection():sendEvent(TogglePTOAttachStateEvent.new(vehicle, attachedVehicle))
        end
    end
end