/**
 * @file
 * @brief TUI LL log helper
 * @copyright (C) 2012 - 2021, Samsung Electronics Co., Ltd.
 */

#include <macros.h>
#include <stdio.h>
#include <string.h>
#include <syscall.h>
#include <unistd.h>

#include "tuill_log.h"

//TODO: delete after SDK update
const char *log_tag = "";
//TODO: uncomment after SDK update
//extern const char *log_tag;

__attribute__ ((visibility("default"))) void _trace_out_(const struct trace_info *info)
{
    char string[CONFIG_SYSLOG_LIMIT];
    char *data = string;
    size_t size = sizeof(string);
    const char *name = strrchr(info->file, '/');
    int ret = snprintf(data, size, "DBG: %s[%d] %s (%s:): out\n",
                       log_tag, info->pid, info->func, name + 1);
    if (ret >= 0 && (size_t)ret < size) {
//TODO: delete after SDK update
        syslog(LOG_DEBUG, "%s", data);
//TODO: uncomment after SDK update
//        ksyslog(LOG_DEBUG, data, ret);
    }
}

__attribute__ ((visibility("default"))) struct trace_info _trace_in_(const char *file,
                                                                     const char *func,
                                                                     const int line)
{
    const struct trace_info info = {file, func, getpid()};
    char string[CONFIG_SYSLOG_LIMIT];
    char *data = string;
    size_t size = sizeof(string);
    const char *name = strrchr(file, '/');
    int ret = snprintf(data, size, "DBG: %s[%d] %s (%s:%d): in\n",
                       log_tag, info.pid, func, name + 1, line);
    if (ret >= 0 && (size_t)ret < size) {
//TODO: delete after SDK update
        syslogtr(LOG_DEBUG, "%s", data);
//TODO: uncomment after SDK update
//        ksyslog(LOG_DEBUG, data, ret);
    }

    return info;
}

__attribute__ ((visibility("default"))) void log_dump(const char *func,
                                                      int line,
                                                      uint8_t *data,
                                                      uint32_t size)
{
#define DH_SYM_PER_LINE 16
    char buff[CONFIG_SYSLOG_LIMIT];
    int ret = sprintf(buff, "printed from %s:%d\n", func, line);
//TODO: delete after SDK update
    syslog(LOG_DEBUG, "%s", buff);
//TODO: uncomment after SDK update
//    ksyslog(LOG_DEBUG, buff, ret);
    for (size_t i = 0; i < size; i += DH_SYM_PER_LINE) {
        int len = 0;
        char *p = buff;
        for (size_t j = 0; j < DH_SYM_PER_LINE && i + j < size; j++) {
            ret = sprintf(p, "%02X ", (uint32_t)((uint8_t *)data)[i + j]);
            len += ret;
            p += ret;
        }

        ret = sprintf(p, "\n");
        len += ret;
//TODO: delete after SDK update
        syslog(LOG_DEBUG, "%s", buff);
//TODO: uncomment after SDK update
//        ksyslog(LOG_DEBUG, buff, len);
    }
}
