-- AdjustableMirrorsEvent.lua
-- MP-Sync event for adjustable mirrors.

AdjustableMirrorsEvent = {}

local AdjustableMirrorsEvent_mt = Class(AdjustableMirrorsEvent, Event)

InitEventClass(AdjustableMirrorsEvent, "AdjustableMirrorsEvent")

function AdjustableMirrorsEvent.emptyNew()
    return Event.new(AdjustableMirrorsEvent_mt)
end

function AdjustableMirrorsEvent.new(vehicle)
    local self = AdjustableMirrorsEvent.emptyNew()
    self.vehicle = vehicle
    return self
end

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

    local count = streamReadUInt8(streamId)
    local data = {}

    for _ = 1, count do
        local name = streamReadString(streamId)
        local rotX = streamReadFloat32(streamId)
        local rotY = streamReadFloat32(streamId)
        local rotZ = streamReadFloat32(streamId)

        data[name] = {
            rotX = rotX,
            rotY = rotY,
            rotZ = rotZ
        }
    end

    if self.vehicle ~= nil and self.vehicle:getIsSynchronized() then
        for name, values in pairs(data) do
            AdjustableMirrors.setMirrorOffset(
                self.vehicle,
                name,
                values.rotX,
                values.rotY,
                values.rotZ,
                true
            )
        end
    end

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

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

    local spec = self.vehicle ~= nil and self.vehicle.spec_adjustableMirrors or nil
    local count = 0

    if spec ~= nil and spec.mirrors ~= nil then
        for _ in pairs(spec.mirrors) do
            count = count + 1
        end
    end

    streamWriteUInt8(streamId, count)

    if count > 0 then
        for name, mirror in pairs(spec.mirrors) do
            streamWriteString(streamId, name)
            streamWriteFloat32(streamId, mirror.targetRotX or mirror.rotX or 0)
            streamWriteFloat32(streamId, mirror.targetRotY or mirror.rotY or 0)
            streamWriteFloat32(streamId, mirror.targetRotZ or mirror.rotZ or 0)
        end
    end
end

function AdjustableMirrorsEvent.sendEvent(vehicle, noEventSend)
    if noEventSend == true then
        return
    end

    if vehicle == nil then
        return
    end

    if g_server ~= nil then
        g_server:broadcastEvent(AdjustableMirrorsEvent.new(vehicle), nil, nil, vehicle)
    elseif g_client ~= nil then
        g_client:getServerConnection():sendEvent(AdjustableMirrorsEvent.new(vehicle))
    end
end