/*
 * wnix, a Unix-like operating system for WebAssembly applications.
 * Copyright (C) 2025  Xavier Del Campo Romero
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */

#include <kprintf.h>
#include <io.h>
#include <fcntl.h>
#include <stddef.h>
#include <stdarg.h>
#include <printf.h>
#include <time.h>

struct kvprintf
{
    struct fs_fd fd;
    size_t n;
};

static void writechar(const char c, void *const args)
{
    static char buf[128];
    static size_t bufi;
    struct kvprintf *k = args;

    buf[bufi++] = c;

    if (c == '\n' || bufi >= sizeof buf)
    {
        const struct fs_write w =
        {
            .buf = buf,
            .fd = &k->fd,
            .n = bufi
        };

        io_write(&w);
        bufi = 0;
    }

    k->n++;
}

int ktvprintf(const bool time, const char *const fmt, va_list ap)
{
    struct timespec ts;
    struct kvprintf k = {0};
    const struct fs_open o =
    {
        .fd = &k.fd,
        .path = "/dev/tty",
        .mode = O_WRONLY
    };

    if (time && clock_gettime(CLOCK_REALTIME, &ts))
        return -1;

    const long ms = ts.tv_nsec / 1000000;

    if (io_open(&o)
        || (time
            && fctprintf(writechar, &k, "[%lld.%03ld] ", ts.tv_sec, ms) < 0)
        || fctvprintf(writechar, &k, fmt, ap) < 0)
        return -1;

    return k.n;
}
