/***************************************************************************
                          log.c  -  description
                             -------------------
    begin                : mi�� jul 16 2003
    copyright            : (C) 2003 by Damian Serrano Garcia
    email                : dserrano@alumnos.upm.es
 ***************************************************************************/

#include "log.h"

log_t *init_log_cc (log_t *log, int id) {
  char log_filename[2048];

  createSemaphore(1, & log->sema_log);
  sprintf(log_filename, "%s/cc%d.log", getenv("RECOVERY_LOG"), id);
  if ((log->file = fopen(log_filename, "w+b")) == NULL){
    log->file = NULL;
    return log;
  }

  return log;
}

log_t *init_log_qm (log_t *log, int id) {
  char log_filename[2048];

  createSemaphore(1, & log->sema_log);
  sprintf(log_filename, "%s/qm%d.log", getenv("RECOVERY_LOG"), id);
  if ((log->file = fopen(log_filename, "wt")) == NULL){
    log->file = NULL;
    return log;
  }

  return log;
}

log_t *init_log_flag (log_t *log, char* file_name) {
  char log_filename[2048];

  createSemaphore(1, & log->sema_log);
  sprintf(log_filename, "%s/flag_%s.log", getenv("RECOVERY_LOG"), file_name);
  if ((log->file = fopen(log_filename, "wt")) == NULL){
    log->file = NULL;
    return log;
  }

  return log;
}


int write_in_log_cc (log_t *log, char *buffer, int length) {
  int chars;

  /*
  if ((chars = fputs(buffer, file)) == EOF){
    return -1;
  }
  */

  decSemaphore(& log->sema_log);
  fwrite(buffer, length, 1, log->file);
  fflush(log->file);
  incSemaphore(& log->sema_log);

  /*if (fputs("\n", file) == EOF){
    return -1;
  }*/

  return chars;
}

int write_in_log_qm (log_t *log, char *buffer) {
  int chars;

  decSemaphore(& log->sema_log);
  if ((chars = fputs(buffer, log->file)) == EOF){
    chars = -1;
  }
  fflush(log->file);
  incSemaphore(& log->sema_log);

//printf("write_in_logQM <%s> <%d>\n", buffer, chars);
  /*if (fputs("\n", file) == EOF){
    return -1;
  }*/

  return chars;
}

int write_in_log_flag (log_t *log, char *buffer) {
  int chars;

  decSemaphore(& log->sema_log);
  if ((chars = fputs(buffer, log->file)) == EOF){
    chars = -1;
  }
  fflush(log->file);
  incSemaphore(& log->sema_log);

//printf("write_in_logQM <%s> <%d>\n", buffer, chars);
  /*if (fputs("\n", file) == EOF){
    return -1;
  }*/

  return chars;
}

int close_log (log_t *log) {
  decSemaphore(& log->sema_log);
  if (fclose(log->file) != 0){
    incSemaphore(& log->sema_log);
    return -1;
  } else {
    incSemaphore(& log->sema_log);
    return 0;
  }
}



