#include "utilities.h"
#include <cstdio>
#include <cstdarg>

std::string string_format(const std::string fmt, ...) {
    int size = ((int)fmt.size()) * 2 + 50;
    std::string str;
    va_list ap;
    while (1) {
        str.resize(size);
        va_start(ap, fmt);
        int n = vsnprintf((char *)str.data(), size, fmt.c_str(), ap);
        va_end(ap);
        if (n > -1 && n < size) {
            str.resize(n);
            return str;
        }
        if (n > -1)
            size = n + 1;
        else
            size *= 2;
    }
    return str;
}

void OdinUtilities::ThrowNapiException(Napi::Env env, OdinError error, const char* message)
{
    const char* lastError = odin_error_get_last_error();
    std::string text = string_format("%s: ErrorCode=%d Details=%s", message, (int)error, lastError ? lastError : "");

    Napi::TypeError::New(env, text.c_str()).ThrowAsJavaScriptException();
}