#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include <stdio.h>
#include <string.h>
#include <pslib.h>
#include "pmConfig.h"
#include "pmConfigCommand.h"

bool pmConfigDatabaseCommand(psString *command, const pmConfig *config)
{
    PS_ASSERT_PTR_NON_NULL(command, false);
    PS_ASSERT_PTR_NON_NULL(config, false);
    PS_ASSERT_PTR_NON_NULL(config->complete, false);

    bool mdok;                          // Status of MD lookup
    const char *dbserver = psMetadataLookupStr(&mdok, config->complete, "DBSERVER"); // Database server
    if (!mdok || strlen(dbserver) == 0) {
        psError(PS_ERR_UNEXPECTED_NULL, true, "Unable to find DBSERVER in site configuration.\n");
        return false;
    }
    const char *dbname = psMetadataLookupStr(&mdok, config->complete, "DBNAME"); // Database name
    if (!mdok || strlen(dbname) == 0) {
        psError(PS_ERR_UNEXPECTED_NULL, true, "Unable to find DBNAME in site configuration.\n");
        return false;
    }
    const char *dbuser = psMetadataLookupStr(&mdok, config->complete, "DBUSER"); // Database user
    if (!mdok || strlen(dbuser) == 0) {
        psError(PS_ERR_UNEXPECTED_NULL, true, "Unable to find DBUSER in site configuration.\n");
        return false;
    }
    const char *dbpassword = psMetadataLookupStr(&mdok, config->complete, "DBPASSWORD"); // Database password
    if (!mdok || strlen(dbpassword) == 0) {
        psError(PS_ERR_UNEXPECTED_NULL, true, "Unable to find DBPASSWORD in site configuration.\n");
        return false;
    }

    psStringAppend(command, " -dbserver %s -dbname %s -dbuser %s -dbpassword %s",
                   dbserver, dbname, dbuser, dbpassword);

    return true;
}


bool pmConfigTraceCommand(psString *command)
{
    PS_ASSERT_PTR_NON_NULL(command, false);

    psMetadata *levels = psTraceLevels(); // Metadata levels
    psMetadataIterator *iter = psMetadataIteratorAlloc(levels, PS_LIST_HEAD, NULL); // Iterator for levels
    psMetadataItem *item;               // Item from iteration
    while ((item = psMetadataGetAndIncrement(iter))) {
        assert(item->type == PS_TYPE_S32);
        psStringAppend(command, " -trace %s %d", item->name, item->data.S32);
    }
    psFree(iter);
    psFree(levels);

    return true;
}
