#include <stdio.h>
#include "DebugService.h"
#include "MemoryMapInputBroker.h"
#include "ConfigurationDatabase.h"
#include "ObjectRegistryDatabase.h"
#include "ClassRegistryDatabase.h"

using namespace MARTe;

#include <unistd.h>
#include <signal.h>

void timeout_handler(int sig) {
    printf("Test timed out!\n");
    _exit(1);
}

int main() {
    signal(SIGALRM, timeout_handler);
    alarm(5); // 5 seconds timeout
    printf("MARTe2 Debug Suite Integration Test\n");

    {
        // 1. Manually trigger Registry Patching
        DebugService service;
        ConfigurationDatabase serviceData;
        serviceData.Write("ControlPort", (uint16)9090);
        service.Initialise(serviceData);
        
        printf("DebugService initialized and Registry Patched.\n");

        // 2. Try to create a MemoryMapInputBroker
        ClassRegistryItem *item = ClassRegistryDatabase::Instance()->Find("MemoryMapInputBroker");
        if (item != NULL_PTR(ClassRegistryItem *)) {
            Object *obj = item->GetObjectBuilder()->Build(GlobalObjectsDatabase::Instance()->GetStandardHeap());
            if (obj != NULL_PTR(Object *)) {
                printf("Instantiated Broker Class: %s\n", obj->GetClassProperties()->GetName());
                printf("Success: Broker patched and instantiated.\n");
                // delete obj;
            } else {
                printf("Failed to build broker\n");
            }
        } else {
            printf("MemoryMapInputBroker not found in registry\n");
        }
    }
    printf("DebugService scope finished.\n");

    return 0;
}
