-- =========================================================
-- Speed Camera BR — Config Sync Event (Server -> Clients)
-- =========================================================
-- Sincroniza a configuração (fazenda destino, taxa, enabled) do
-- servidor pra todos os clientes. Disparado quando o admin muda algo,
-- e quando um cliente entra na partida.

SC_ConfigSyncEvent = {}
SC_ConfigSyncEvent_mt = Class(SC_ConfigSyncEvent, Event)

InitEventClass(SC_ConfigSyncEvent, "SC_ConfigSyncEvent")

function SC_ConfigSyncEvent.emptyNew()
    return Event.new(SC_ConfigSyncEvent_mt)
end

function SC_ConfigSyncEvent.new()
    return SC_ConfigSyncEvent.emptyNew()
end

function SC_ConfigSyncEvent:writeStream(streamId, connection)
    streamWriteInt32(streamId,  SpeedCameraConfig.destFarmId or 0)
    streamWriteFloat32(streamId, SpeedCameraConfig.transactionFee or 1.0)
    streamWriteBool(streamId,   SpeedCameraConfig.enabled ~= false)
end

function SC_ConfigSyncEvent:readStream(streamId, connection)
    SpeedCameraConfig.destFarmId     = streamReadInt32(streamId)
    SpeedCameraConfig.transactionFee = streamReadFloat32(streamId)
    SpeedCameraConfig.enabled        = streamReadBool(streamId)
    self:run(connection)
end

function SC_ConfigSyncEvent:run(connection)
    -- No cliente, só aplica (já feito no readStream)
    print(string.format(
        "[SpeedCameraBR] [CLIENT] Config sincronizada: destFarmId=%d",
        SpeedCameraConfig.destFarmId or 0))
end

-- Servidor envia pra todos os clientes
function SC_ConfigSyncEvent.broadcast()
    if not g_server then return end
    g_server:broadcastEvent(SC_ConfigSyncEvent.new())
end

-- Servidor envia pra um cliente específico (quando ele entra)
function SC_ConfigSyncEvent.sendToClient(connection)
    if not g_server or connection == nil then return end
    connection:sendEvent(SC_ConfigSyncEvent.new())
end
