#include "BasicTCPSocket.h"
#include "BasicUDPSocket.h"
#include "DebugService.h"
#include "ObjectRegistryDatabase.h"
#include "StandardParser.h"
#include "StreamString.h"
#include "HighResolutionTimer.h"
#include "TestCommon.h"
#include <assert.h>
#include <stdio.h>

using namespace MARTe;

void TestFullTracePipeline() {
    printf("Starting Full Trace Pipeline Test...\n");
    
    ObjectRegistryDatabase::Instance()->Purge();

    // 1. Setup Service
    DebugService service;
    ConfigurationDatabase config;
    config.Write("ControlPort", (uint16)8082);
    config.Write("StreamPort", (uint16)8083);
    config.Write("LogPort", (uint16)8084);
    config.Write("StreamIP", "127.0.0.1");
    assert(service.Initialise(config));
    Sleep::MSec(500);

    // 2. Register a mock signal
    uint32 mockValue = 0;
    DebugSignalInfo* sig = service.RegisterSignal(&mockValue, UnsignedInteger32Bit, "TraceTest.Signal", 0, 1);
    assert(sig != NULL_PTR(DebugSignalInfo*));
    printf("Signal registered with ID: %u\n", sig->internalID);

    // 3. Enable Trace via the real API (DebugService::TraceSignal), not by
    // poking isTracing directly — DebugService's override also flags
    // udpsConfigPending so the streamer thread rebuilds its UDPS slot table
    // and CONFIG packet. Without that, the streamer's anyData/slot-match
    // logic (DebugService.cpp Streamer()) never finds a slot for this
    // signal's samples and silently never sends any DATA packet at all.
    assert(service.TraceSignal("TraceTest.Signal", true, 1) == 1u);

    // 4. Setup a local UDP listener
    BasicUDPSocket listener;
    assert(listener.Open());
    assert(listener.Listen(8083));
    GrowUDPRecvBuffer(listener);

    // 5. Simulate cycles
    printf("Simulating cycles...\n");
    for (int i=0; i<50; i++) {
        mockValue = 1000 + i;
        uint64 ts = (uint64)((float64)HighResolutionTimer::Counter() * HighResolutionTimer::Period() * 1000000.0);
        service.ProcessSignal(sig, sizeof(uint32), ts);
        Sleep::MSec(10);
    }

    // 6. Try to read a real UDPS DATA packet from UDP
    uint32 val = 0;
    if (ReadUDPSTraceScalar(listener, 2000, val)) {
        printf("SUCCESS: Received UDPS DATA packet! Value=%u\n", val);
    } else {
        printf("FAILURE: No UDP packets received.\n");
    }

    listener.Close();
}
