#include <glib.h>

#include "../public/errors.h"
#include "../public/version.h"

//
// PRIVATE CONSTANTS
//
static const gchar* S_KEYFILE_GROUP = "Version";

//
// FORWARD DECLARATIONS
//
gboolean ensure_keyfile(void);
gchar* get_keyfile_entry(
    const gchar* key
);

//
// STATIC DATA
//
static gboolean  s_keyfile_loaded;
static GKeyFile* s_keyfile_version;

static const gchar* S_KEYS[] = {
    "SkuPrettyName",
    "SkuName",
    "SkuEdition",
    "SkuTagline",
    "VersionMajor",
    "VersionMinor",
    "VersionBuild",
    "VersionDatetime",
    "BuildBranch",
    "BuildDatestamp",
    "BuildHash",
    "BuildUser",
    "BuildTag",
    "VersionString"
};
static const gchar* S_DEFAULT_VALUES[] = {
    "Unknown System",
    "Unknown System",
    "",
    "",
    "0",
    "0",
    "0",
    "0",
    "unknown",
    "000000-0000",
    "unknown",
    "unknown",
    "no tag",
    "0.0.0.0"
};
static gchar* S_VALUES[G_N_ELEMENTS(S_KEYS)] = { 0 };

//
// PUBLIC FUNCTIONS
//
gboolean wintc_build_is_debug(void)
{
#ifdef WINTC_CHECKED
    return TRUE;
#else
    return FALSE;
#endif
}

const gchar* wintc_build_query(
    guint query_id
)
{
    if (query_id >= G_N_ELEMENTS(S_KEYS))
    {
        g_critical("comgtk: version query for %d is invalid", query_id);
        return NULL;
    }

    // Does a value exist already?
    //
    if (S_VALUES[query_id])
    {
        return S_VALUES[query_id];
    }

    // Attempt to load from key file
    //
    if (ensure_keyfile())
    {
        S_VALUES[query_id] =
            g_key_file_get_string(
                s_keyfile_version,
                S_KEYFILE_GROUP,
                S_KEYS[query_id],
                NULL
            );

        return S_VALUES[query_id];
    }

    // Otherwise return default value
    //
    return S_DEFAULT_VALUES[query_id];
}

//
// PRIVATE FUNCTIONS
//
gboolean ensure_keyfile(void)
{
    GError* error = NULL;

    if (s_keyfile_loaded)
    {
        return TRUE;
    }

    if (!s_keyfile_version)
    {
        s_keyfile_version = g_key_file_new();
    }

    s_keyfile_loaded =
        g_key_file_load_from_file(
            s_keyfile_version,
            "@CMAKE_INSTALL_PREFIX@/@WINTC_ASSETS_INSTALL_DIR@/release",
            G_KEY_FILE_NONE,
            &error
        );

    wintc_log_error_and_clear(&error);

    return s_keyfile_loaded;
}
