/*
 * log.c
 *
 * Copyright (C) 2018 Aleksandar Andrejevic <theflash@sdf.lonestar.org>
 *
 * 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 <http://www.gnu.org/licenses/>.
 */

#include <log.h>
#include <device.h>
#include <lock.h>
#include <stdio.h>
#include <timer.h>

#define QUEUE_SIZE 4096

typedef struct
{
    log_level_t level;
    char message[MAX_LOG_MESSAGE_SIZE];
} log_entry_t;

static DECLARE_LOCK(lock);
static log_entry_t queue[QUEUE_SIZE];
static bool_t empty = TRUE;
static dword_t start = 0, end = 0;

char *debug_channel = NULL;
#ifdef DEBUG
log_level_t debug_min_level = LOG_DEBUG;
#else
log_level_t debug_min_level = LOG_NORMAL;
#endif

static void flush_queue(void)
{
    if (!debug_channel) return;
    device_t *device = get_char_device(debug_channel);
    if (!device) return;
    lock_acquire(&lock);

    while (!empty)
    {
        if (queue[start].level >= debug_min_level)
        {
            size_t written;
            if (device_write(device, queue[start].message, 0ULL, strlen(queue[start].message), &written) != ERR_SUCCESS) break;
        }

        start++;
        start %= QUEUE_SIZE;
        if (start == end) empty = TRUE;
    }

    lock_release(&lock);
}

void append_log_entry(const char *source, log_level_t level, const char *message)
{
    size_t length = strlen(message);
    if (length == 0) return;

    bool_t too_big = FALSE;
    size_t max_size = MAX_LOG_MESSAGE_SIZE - 4 - strlen(source);
    if (length >= max_size)
    {
        length = max_size - 3;
        too_big = TRUE;
    }

    char message_copy[length + 1];
    strncpy(message_copy, message, length);
    message_copy[length] = '\0';
    if (too_big) strcat(message_copy, "...");

    lock_acquire(&lock);
    queue[end].level = level;
    snprintf(queue[end].message, MAX_LOG_MESSAGE_SIZE, "[%s] %s\n", source, message_copy);

    if (start == end && !empty)
    {
        start++;
        start %= QUEUE_SIZE;
    }

    end++;
    end %= QUEUE_SIZE;
    empty = FALSE;

    lock_release(&lock);
    flush_queue();
}
