/*
 * XFCE plugin for the MOC player
 * 
 * Control the MOC (Media On Console) player from the XFCE panel!
 * 
 * Author: Jakub Krauz
 * E-mail: jakub.krauz@volny.cz
 * Univerzity of West Bohemia
 * Department of Computer Science and Engineering
 * Pilsen, 2012
 */

#include <limits.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

#include <logger.h>


#undef _DEBUG
//#define _DEBUG    // if defined, DBG-level logging messages are printed to the logfile


#define LOGFILE_NAME  "~/.moc/xfce4-mocp-plugin_log"

#define DATE_LEN      20    // length of the date-time string used in logging messages


/* Function prototypes */
static char* logfname();
static char* datetime_now(char* str);


/**
 * Logs the given message to the logfile. If the file cannot be opened the message is
 * printed to stderr.
 * @param type Type of the log message. Predefined values are ERR, WARN and DBG.
 * @param format Printf-style format string.
 * @param ... Arguments for the format string.
 * @return 0 on succes, 1 on error opening the logfile
 */
int logit(LOGTYPE type, const char* format, ...)
{
  FILE *f;
  va_list argptr;
  char date_str[DATE_LEN];
  int retval = 0;
  
#ifndef _DEBUG
  if (type == DBG)
    return;  // do not print DBG-level messages
#endif
  
  if ((f = fopen(logfname(), "a")) == NULL)
  {
    fprintf(stderr, "Error opening logfile \"%s\". Writing to stderr.\n", logfname());
    f = stderr;
    retval = 1;
  }
  fprintf(f, "%s ", datetime_now(date_str));
  if (type == ERR)
    fprintf(f, "ERROR: ");
  else if (type == WARN)
    fprintf(f, "WARNING: ");
  va_start(argptr, format);
  vfprintf(f, format, argptr);
  va_end(argptr);
  fputc('\n', f);
  if (f != stderr)
    fclose(f);
  
  return retval;
}


/**
 * Creates the name of the logging file.
 * @return Filename. The string was not malloced so it should not be freed.
 */
static char* logfname()
{
  static char logfname[PATH_MAX];
  static int logfname_set = 0;
  char *homedir;

  if (!logfname_set)  // the filename does not change - set it only once
  {
    homedir = getenv("HOME");
    snprintf(logfname, sizeof (logfname), "%s/%s", homedir, LOGFILE_NAME + 2);
    logfname_set = 1;
  }

  return logfname;
}


/**
 * Writes the current date and time (yyyy-mm-dd hh:mm:ss) to the given string.
 * The memory for the string must be allocated before.
 * @param str Pointer to the string to write in.
 * @return String with date and time.
 */
static char* datetime_now(char* str)
{
  time_t now;
  struct tm *ptm;
  
  time(&now);
  ptm = localtime(&now);
  strftime(str, DATE_LEN, "%Y-%m-%d %H:%M:%S", ptm);
  
  return str;
}
