/*
 * @file tl_log.c
 * @brief softsim log
 * Copyright (c) 2016, Samsung Electronics Corporation. All rights reserved.
 */
/*#include <comdef.h>*/

#include "target.h"
#include <stdlib.h>
#include <stdio.h>
#include <stdarg.h>
#include "common.h"
#include "target.h"
#include "tl_log.h"
#include "tl_utils.h"

static cmd_rsp_t *global_rsp = NULL;
static const uint32_t max_log_len = SOFTSIM_LOG_BUF_LEN;

void init_log(cmd_req_t *req, cmd_rsp_t *rsp) {
    global_rsp = rsp;
    global_rsp->log_len = 0;
}

uint32_t get_log_pos(){
    return global_rsp->log_len;
}

void close_log() {
    global_rsp = NULL;
}

static void log_to_global_buf(uint8_t *log, uint32_t size) {

    /* if global log buffer is not available, skip it */
    if (global_rsp == NULL) {
        return;
    }

    uint32_t log_len = global_rsp->log_len;

    /* don't exceed the log buffer limit */
    if (log_len + size > max_log_len) {
#ifdef USE_QSEE
        qsee_log(QSEE_LOG_MSG_DEBUG, "dump log due to no room for log output");
#elif USE_MOBICORE
#error "MOBICORE not implemented yet..."
#elif USE_BLOWFISH
        printf("dump log due to no room for log output\n");
#else
#error "TEE plaform not defined yet"
#endif
        return;
    }
    log[size-1] = '\n';
    memcpy(global_rsp->logbuf + log_len, log, size);
    global_rsp->log_len = log_len + size;
}

#define LOCAL_LOG_BUF_SIZE 256
uint8_t log_buf[LOCAL_LOG_BUF_SIZE];

static int in_log = 0;

void tl_log(int level, const char *fmt, ...) {

    /* avoid infinite recursive log */
    if (in_log)
        return;

    in_log = 1;
    /* get the full log string */
    va_list ap;
    va_start(ap, fmt);
    int rc = vsnprintf((char*)log_buf, LOCAL_LOG_BUF_SIZE, fmt, ap);
    va_end(ap);
    if (rc >= LOCAL_LOG_BUF_SIZE) {
       rc = LOCAL_LOG_BUF_SIZE;
    } else {
       rc = rc + 1;
    }

    /* log to the system log */
    log_buf[rc-1] = '\0';
    /*target_printf((char*)log_buf);*/
#ifndef _NDEBUG_
#ifdef USE_QSEE
    qsee_log(level, "%s", (char*)log_buf);
#elif USE_MOBICORE
#error "MOBICORE not implemented yet..."
#elif USE_BLOWFISH
    printf("%s\n", (char*)log_buf);
#else
#error "TEE plaform not defined yet"
#endif
#endif
    /* log to the global log buffer */
    log_to_global_buf(log_buf, rc);

    in_log = 0;
    return;
}
