//
// Created by jedi on 18.11.21.
//

#include "log.h"

#include <espressif/esp_common.h>

constexpr unsigned syslog_buffer_size = 1024;
char syslog_buf[syslog_buffer_size];
volatile unsigned head = 0;
volatile unsigned streams = 0;

extern "C" void syslog(const char *msg) {
    printf("syslog> %s", msg);
    while (char c = *msg++) {
        syslog_buf[head++ % syslog_buffer_size] = c;
    }
    syslog_buf[head] = 0;
}

unsigned syslog_current_tail() {
    if(head < syslog_buffer_size)
        return 0;
    return head + 1 - syslog_buffer_size;
}

unsigned syslog_data_after(unsigned local_tail) {
    if(local_tail > head)
        return 0;
    return (head % syslog_buffer_size) - (local_tail % syslog_buffer_size);
}

extern "C" int syslog_copy_out(char *out, int len, unsigned local_tail) {
    unsigned cnt = 0;
//    printf("<syslog(%d): [%d, %d] `%.*s`\n", streams, (local_tail & syslog_buffer_size), head,
//           head - (local_tail & syslog_buffer_size), &syslog_buf[local_tail % syslog_buffer_size]);
    while (cnt < syslog_data_after(local_tail) && cnt < len) {
        out[cnt] = syslog_buf[local_tail % syslog_buffer_size + cnt];
        cnt++;
    }
    return cnt;
}

extern "C" void syslog_attach() {
    streams++;
}

extern "C" void syslog_detach() {
    streams--;
}