-- =========================================================
-- Speed Camera BR — Radar Config Event (cliente <-> servidor)
-- =========================================================
-- Quando um cliente configura um radar pelo R (limite + 3 multas),
-- este evento leva os valores até o SERVIDOR, que aplica, salva e
-- rebroadcasta pra todos os clientes. Assim a config persiste no MP.
-- =========================================================

SC_RadarConfigEvent = {}
SC_RadarConfigEvent_mt = Class(SC_RadarConfigEvent, Event)

InitEventClass(SC_RadarConfigEvent, "SC_RadarConfigEvent")

function SC_RadarConfigEvent.emptyNew()
    return Event.new(SC_RadarConfigEvent_mt)
end

-- Cria o evento com o radar-alvo e os valores
function SC_RadarConfigEvent.new(placeable, speedLimit, costPerKMH)
    local self = SC_RadarConfigEvent.emptyNew()
    self.placeable  = placeable
    self.speedLimit = speedLimit
    self.costPerKMH = costPerKMH
    return self
end

function SC_RadarConfigEvent:writeStream(streamId, connection)
    NetworkUtil.writeNodeObject(streamId, self.placeable)
    streamWriteFloat32(streamId, self.speedLimit)
    streamWriteInt32(streamId, self.costPerKMH)
end

function SC_RadarConfigEvent:readStream(streamId, connection)
    self.placeable  = NetworkUtil.readNodeObject(streamId)
    self.speedLimit = streamReadFloat32(streamId)
    self.costPerKMH = streamReadInt32(streamId)
    self:run(connection)
end

function SC_RadarConfigEvent:run(connection)
    -- Aplica os valores no radar-alvo
    if self.placeable ~= nil and self.placeable.applyConfigValues ~= nil then
        self.placeable:applyConfigValues(self.speedLimit, self.costPerKMH, 0, 0)
    end

    -- Se sou o SERVIDOR e recebi de um cliente, rebroadcast pros outros
    if not connection:getIsServer() then
        if g_server ~= nil then
            g_server:broadcastEvent(
                SC_RadarConfigEvent.new(self.placeable, self.speedLimit, self.costPerKMH),
                nil, connection, self.placeable)
        end
    end
end

-- Envia a config (cliente → servidor, ou servidor → todos)
function SC_RadarConfigEvent.send(placeable, speedLimit, costPerKMH)
    local event = SC_RadarConfigEvent.new(placeable, speedLimit, costPerKMH)
    if g_server ~= nil then
        g_server:broadcastEvent(event, nil, nil, placeable)
    else
        g_client:getServerConnection():sendEvent(event)
    end
end
