/*
 * Yet another daemon library especially designed to be used
 * with libsxmp based daemons.
 *
 * (c) Alexander Vdolainen 2016 <avdolainen@zoho.com>
 *
 * libsxmp is free software: you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as published
 * by the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * libsxmp 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 Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.";
 *
 */

#include <stdlib.h>
#include <stdio.h>
#include <stdarg.h>
#include <errno.h>
#include <string.h>
#include <pthread.h>
#include <ctype.h>
#include <dlfcn.h>
#include <time.h>

#include <tdata/usrtc.h>
#include <sexpr/sexp.h>

#include <ydaemon/ydaemon.h>

void ydlog(yd_context_t *ctx, int olvl, const char *fmt, ...)
{
  yd_log_t *log = ctx->logcontext;
  FILE *logstr = NULL;
  char tbuf[32];
  struct tm tmb;
  time_t ctime;
  va_list args;

  if(!log) return;
  if(!(logstr = log->logstream)) return;

  if(olvl >= log->verbose_level) { /* we can output this */
    /* take a time and output this */
    time(&ctime);
    localtime_r(&ctime, &tmb);
    asctime_r(&tmb, tbuf);
    /* remove trailing \n */
    tbuf[strlen(tbuf) - 1] = '\0';
    fprintf(logstr, "[%s] ", tbuf);
    switch(olvl) { /* out prefix */
    case YL_DEBUG: fprintf(logstr, "[DEBUG] "); break;
    case YL_INFO: fprintf(logstr, "[INFO] "); break;
    case YL_WARN: fprintf(logstr, "[WARNING] "); break;
    case YL_ERROR: fprintf(logstr, "[ERROR] "); break;
    default: return;
    }

    va_start(args, fmt);
    vfprintf(logstr, fmt, args);
    va_end(args);
  }

  return;
}