/*
 * This is a little utility for querying the SICS mongo DB log. 
 *
 * copyright: GPL
 *
 * Mark Koennecke, February 2016
 */
#include <sicslogquery.h>
#include <bson.h>
#include <logv2.h>

void formatSeverity(unsigned int severity, char *buffer, unsigned int bufferLength)
{
  static const char *severityText[] = {"FATAL",
			       "ERROR",
                               "WARNING",
                               "INFO",
                               "VERBOSE",
                               "DEBUG",
                               "INVALID"
                                };

  if(severity > DEBUG){
    severity = INVALID;
  }
  strncpy(buffer,severityText[severity-1],bufferLength);
} 

/*----------------------------------------------------------------------------------------*/
static void  ResultPrint(const bson_t *doc, void *userData)
{
  bson_iter_t iter;
  unsigned int severity;
  int length;
  const char *message, *timeText, *sub;
  char sevBuf[20];

  bson_iter_init(&iter,doc);
  bson_iter_find(&iter,"timetext");
  timeText = bson_iter_utf8(&iter,&length);
  bson_iter_init(&iter,doc);
  bson_iter_find(&iter,"severity");
  severity = bson_iter_int32(&iter);
  formatSeverity(severity,sevBuf,sizeof(sevBuf));
  bson_iter_find(&iter,"sub");
  sub = bson_iter_utf8(&iter,&length);
  bson_iter_find(&iter,"message");
  message = bson_iter_utf8(&iter,&length);

  fprintf(stdout,"%s    %s   %s   %s\n",timeText,sevBuf, sub, message); 
  
}

int main(int argc, char *argv[])
{
  int status;
  char *error;

  sicslogSetup("mongodb://logwriter:sinqsics@mpc1965:27017/?authSource=admin",NULL);
  status = sicslogQuery(argc,argv,ResultPrint,NULL);
  if(status != 0){
    error = sicslogGetError();
    fprintf(stdout,"%s\n", error);
  }
  return status;
}

