#include "log_local.h"

int log_local(char *log_fn, char *msg)
{
  FILE *log_fp;

  if (log_fn)
    log_fp = fopen(log_fn, "a+");
  else
    log_fp = fopen(LOG_LOCAL_DEFAULT_LOGFILE, "a+");

  if (!log_fp)
    return -1;


  fprintf(log_fp, msg);
  fclose(log_fp);

  return 0;
  
}

int log_local_message_record(char *log_fn, char *prefix, struct message_record *msg)
{
  int i;
  static char *buf = NULL;
  if (!buf)
    buf = malloc(sizeof(char)*8*8192);
  memset(buf, 0, sizeof(char)*8*8192);

  sprintf(buf, "%s: header usec_time: %lli,", prefix ? prefix : " ", msg->header.usec_time);
  if (log_local(log_fn, buf)<0) 
    return -1;

  sprintf(buf, "%s: header mailbox_name: %s,", prefix ? prefix : " ", msg->header.mailbox_name);
  if (log_local(log_fn, buf)<0) 
    return -1;

  sprintf(buf, "%s: header payload_length: %i,", prefix ? prefix : " ", msg->header.payload_length);
  if (log_local(log_fn, buf)<0) 
    return -1;

  sprintf(buf, "%s: header sender(pid_t): %i,", prefix ? prefix : " ", (int)msg->header.sender);
  if (log_local(log_fn, buf)<0) 
    return -1;

  sprintf(buf, "%s: header from_fd: %i,", prefix ? prefix : " ", (int)msg->header.from_fd);
  if (log_local(log_fn, buf)<0) 
    return -1;

  sprintf(buf, "%s: payload(ascii): ", prefix ? prefix : " ");
  if (log_local(log_fn, buf)<0) 
    return -1;

  buf[0] = '\0';
  for (i=0; i < msg->header.payload_length; i++)
    buf[i] = ( isprint(msg->payload[i]) ? msg->payload[i] : '.' );
  buf[i] = '\n';
  if (log_local(log_fn, buf)<0) 
    return -1;

  sprintf(buf, "%s: payload(hex): ", prefix ? prefix : " ");
  if (log_local(log_fn, buf)<0) 
    return -1;

  buf[0] = '\0';
  for (i=0; i < msg->header.payload_length; i++)
  {
    buf[3*i] = ' ';
    sprintf(buf + 3*i + 1, "%02x", (unsigned char)(msg->payload[i]) );
  }
  buf[3*i] = '\n';
  if (log_local(log_fn, buf)<0) 
    return -1;

  return 0;
}

