----------------------------------------------------------------------------------------------------
-- FreeFloatComponentJointsEvent
----------------------------------------------------------------------------------------------------
-- Purpose: Event to sync the free float state.
--
-- Copyright (c) Wopster, 2021
--
-- FS 22 (c) Ifko[nator], 2023
----------------------------------------------------------------------------------------------------

---@class FreeFloatComponentJointsEvent
FreeFloatComponentJointsEvent = {};

local FreeFloatComponentJointsEvent_mt = Class(FreeFloatComponentJointsEvent, Event);

InitEventClass(FreeFloatComponentJointsEvent, "FreeFloatComponentJointsEvent");

function FreeFloatComponentJointsEvent.emptyNew()
    local self = Event.new(FreeFloatComponentJointsEvent_mt);

    return self;
end;

function FreeFloatComponentJointsEvent.new(vehicle, isFreeFloating)
    local self = FreeFloatComponentJointsEvent.emptyNew();

    self.vehicle = vehicle;
    self.isFreeFloating = isFreeFloating;

    return self;
end;

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

    streamWriteBool(streamId, self.isFreeFloating);
end;

function FreeFloatComponentJointsEvent:readStream(streamId, connection)
    self.vehicle = NetworkUtil.readNodeObject(streamId);
    self.isFreeFloating = streamReadBool(streamId);

    self:run(connection);
end;

function FreeFloatComponentJointsEvent:run(connection)
    -- Send from server to all clients
    if not connection:getIsServer() then
        g_server:broadcastEvent(self, false, connection, self.vehicle);
    end;

    self.vehicle:setFreeFloatState(self.isFreeFloating, true);
end;

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