// testTime.c -- exercises the time library: wall-clock and monotonic clock reads plus a
// millisecond sleep, driven from a Lua context.

#define _POSIX_C_SOURCE 200809L

#include "calog.h"
#include "calogTime.h"

#include <stdatomic.h>
#include <stdio.h>
#include <time.h>

#define CHECK(cond, msg) checkImpl((cond), (msg), __FILE__, __LINE__)

#define PUMP_LIMIT   4000
#define RESULT_SLOTS 12

static CalogT         *calog      = NULL;
static _Atomic int64_t results[RESULT_SLOTS];
static _Atomic int32_t doneCount   = 0;
static _Atomic int32_t errorCount   = 0;
static int32_t         testsRun     = 0;
static int32_t         testsFailed  = 0;

static int64_t asInt(const CalogValueT *value);
static void    checkImpl(bool condition, const char *message, const char *file, int32_t line);
static int32_t nativeDone(CalogValueT *args, int32_t argCount, CalogValueT *result, void *userData);
static int32_t nativeReport(CalogValueT *args, int32_t argCount, CalogValueT *result, void *userData);
static void    onError(uint64_t contextId, const char *message, void *userData);
static void    pumpUntilDone(int32_t target);


static int64_t asInt(const CalogValueT *value) {
    if (value->type == calogIntE) {
        return value->as.i;
    }
    return (int64_t)value->as.r;
}


static void checkImpl(bool condition, const char *message, const char *file, int32_t line) {
    testsRun++;
    if (!condition) {
        testsFailed++;
        printf("FAIL %s:%d  %s\n", file, line, message);
    }
}


static int32_t nativeDone(CalogValueT *args, int32_t argCount, CalogValueT *result, void *userData) {
    (void)args;
    (void)argCount;
    (void)userData;
    atomic_fetch_add(&doneCount, 1);
    calogValueNil(result);
    return calogOkE;
}


static int32_t nativeReport(CalogValueT *args, int32_t argCount, CalogValueT *result, void *userData) {
    int64_t tag;

    (void)userData;
    calogValueNil(result);
    if (argCount != 2 || (args[0].type != calogIntE && args[0].type != calogRealE)) {
        return calogFail(result, calogErrArgE, "report expects (tag, value)");
    }
    tag = asInt(&args[0]);
    if (tag < 0 || tag >= RESULT_SLOTS) {
        return calogFail(result, calogErrArgE, "report: tag out of range");
    }
    atomic_store(&results[tag], asInt(&args[1]));
    return calogOkE;
}


static void onError(uint64_t contextId, const char *message, void *userData) {
    (void)contextId;
    (void)userData;
    fprintf(stderr, "  [script error] %s\n", (message != NULL) ? message : "(null)");
    atomic_fetch_add(&errorCount, 1);
}


static void pumpUntilDone(int32_t target) {
    struct timespec ts = { 0, 500000 };
    int             i;

    for (i = 0; i < PUMP_LIMIT; i++) {
        calogPump(calog);
        if (atomic_load(&doneCount) >= target) {
            calogPump(calog);
            return;
        }
        nanosleep(&ts, NULL);
    }
}


int main(void) {
    CalogContextT *ctx;
    int32_t        i;

    calog = calogCreate();
    if (calog == NULL) {
        printf("calog create failed\n");
        return 1;
    }
    calogSetErrorHandler(calog, onError, NULL);
    calogRegister(calog, "report", nativeReport, NULL);
    calogRegister(calog, "done", nativeDone, NULL);
    calogTimeRegister(calog);
    for (i = 0; i < RESULT_SLOTS; i++) {
        atomic_store(&results[i], -1);
    }

    ctx = calogContextOpen(calog, &calogLuaEngine);
    calogContextEval(ctx,
        "report(1, (timeNow() > 1600000000) and 1 or 0)\n"          // wall clock is past 2020
        "report(2, (timeMonotonic() >= 0) and 1 or 0)\n"            // monotonic clock is non-negative
        "local a = timeMonotonic()\n"
        "local slept = timeSleep(20)\n"
        "local b = timeMonotonic()\n"
        "report(3, (b - a >= 0.015) and 1 or 0)\n"                  // ~20ms elapsed across the sleep
        "report(4, (slept == nil) and 1 or 0)\n"                    // sleep returns nil
        "report(5, (timeSleep(5.0) == nil) and 1 or 0)\n"           // ms may be a real
        "done()");
    pumpUntilDone(1);

    CHECK(atomic_load(&results[1]) == 1, "timeNow is past 2020");
    CHECK(atomic_load(&results[2]) == 1, "timeMonotonic is non-negative");
    CHECK(atomic_load(&results[3]) == 1, "monotonic clock advances at least ~15ms across a 20ms sleep");
    CHECK(atomic_load(&results[4]) == 1, "timeSleep returns nil");
    CHECK(atomic_load(&results[5]) == 1, "timeSleep accepts a real millisecond count");
    CHECK(atomic_load(&errorCount) == 0, "no uncaught errors");

    calogContextClose(ctx);
    calogDestroy(calog);

    printf("\n%d checks, %d failed\n", testsRun, testsFailed);
    fflush(stdout);
    if (testsFailed != 0) {
        return 1;
    }
    return 0;
}
