#include "TestCommon.h"
#include "ObjectRegistryDatabase.h"
#include "DebugService.h"
#include "StandardParser.h"
#include "GlobalObjectsDatabase.h"
#include <stdio.h>

using namespace MARTe;

namespace MARTe {

void TestMessageCommand() {
    printf("--- Test: Custom MARTe Message (MSG) ---\n");

    ObjectRegistryDatabase::Instance()->Purge();
    Sleep::MSec(1000);

    ConfigurationDatabase cdb;
    const char8 * const msg_test_config = 
    "DebugService = {"
    "    Class = DebugService "
    "    ControlPort = 8120 "
    "    UdpPort = 8121 "
    "    StreamIP = \"127.0.0.1\" "
    "}";

    StreamString ss = msg_test_config;
    ss.Seek(0);
    StandardParser parser(ss, cdb);
    if (!parser.Parse()) {
        printf("ERROR: Failed to parse config\n");
        return;
    }

    // Initialize Service
    ReferenceT<DebugService> service("DebugService", GlobalObjectsDatabase::Instance()->GetStandardHeap());
    service->SetName("DebugService");
    
    cdb.MoveToRoot();
    if (cdb.MoveRelative("DebugService")) {
        if (!service->Initialise(cdb)) {
            printf("ERROR: Failed to initialize DebugService\n");
            return;
        }
    }
    ObjectRegistryDatabase::Instance()->Insert(service);

    if (ObjectRegistryDatabase::Instance()->Find("DebugService").IsValid()) {
        printf("DebugService successfully registered in ORD.\n");
    } else {
        printf("ERROR: DebugService NOT found in ORD.\n");
    }

    printf("Service initialized on port 8120.\n");
    Sleep::MSec(500);

    StreamString reply;
    if (SendCommandGAM(8120, "MSG DebugService UnknownFunc 0 Key1=Val1\\nKey2=Val2\n", reply)) {
        printf("MSG response received: %s", reply.Buffer());
        if (StringHelper::SearchString(reply.Buffer(), "OK MSG") != NULL_PTR(const char8 *)) {
            printf("SUCCESS: Asynchronous message dispatched correctly.\n");
        } else {
            printf("FAILURE: MSG command returned error.\n");
        }
    } else {
        printf("ERROR: MSG command communication failed\n");
    }

    ObjectRegistryDatabase::Instance()->Purge();
}

} // namespace MARTe
