#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "libjalib.h"

#define AP_MESSAGE_BUF_SIZE 4096

static int log_core(char *message_id, char *err_msg, size_t err_size, va_list args,
                    char *out_msg, size_t out_msg_size, CLogLevel *out_level)
{
    char message_fmt[AP_MESSAGE_BUF_SIZE];
    CLogLevel log_level;

    int ret = FindMessageByID(message_id, &log_level, message_fmt, sizeof(message_fmt), err_msg, err_size);

    if (ret == -1 || ret == -2)
        return ret;

    // Format the core message with user args
    vsnprintf(out_msg, out_msg_size, message_fmt, args);

    // Compose final log message
    char buffer_with_id[AP_MESSAGE_BUF_SIZE];
    snprintf(buffer_with_id, sizeof(buffer_with_id), "[%s] %s", message_id, out_msg);

    int wRet = WriteLog(log_level, buffer_with_id, err_msg, err_size);
    if (wRet == -1)
        return -1;

    if (out_level)
        *out_level = log_level;

    return ret; // forward the notification flag (0 or 1)
}

static int ja_log(char *message_id, char *err_msg, size_t err_size, ...)
{
    va_list args;
    va_start(args, err_size);

    char buffer_core[AP_MESSAGE_BUF_SIZE];
    CLogLevel log_level;
    int ret = log_core(message_id, err_msg, err_size, args, buffer_core, sizeof(buffer_core), &log_level);

    va_end(args);

    if (ret == -1 || ret == -2)
        return ret;

    if (ret == 1) // based on notice_flag from FindMessageByID
        return CreateNotiEvent(buffer_core, message_id, log_level, err_msg, err_size);

    return 0;
}

static int write_log(char *message_id, char *err_msg, size_t err_size, ...)
{
    va_list args;
    va_start(args, err_size);

    char buffer_core[AP_MESSAGE_BUF_SIZE];
    int ret = log_core(message_id, err_msg, err_size, args, buffer_core, sizeof(buffer_core), NULL);

    va_end(args);
    return ret; // 1 = notice, 0 = no-notice, -1 = error
}
