/**
 * hermes antispam proxy
 * Copyright (C) 2006, 2007 Juan José Gutiérrez de Quevedo <juanjo@iteisa.com>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; version 2 of the License
 *
 * This program 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * @author Juan José Gutiérrez de Quevedo <juanjo@iteisa.com>
 */
#include "FileLogger.h"

extern Configfile cfg;

FileLogger::FileLogger():linecount(0)
{
  pthread_mutex_init(&mutex,NULL);
  tmpstrings.clear();
}

FileLogger::~FileLogger()
{
  if(!cfg.getKeepFileLocked())
    syncBufferToDisk();
  closeFile();
  pthread_mutex_destroy(&mutex);
}

void FileLogger::openFile(string file)
{
  if(NULL==f&&""!=file)
  {
    f=fopen(file.c_str(),"a");
    if(NULL==f)
      throw Exception(_("Couldn't start file logger, couldn't open ")+cfg.getFileLoggerFilename(),__FILE__,__LINE__);
  }
}

void FileLogger::closeFile()
{
  if(NULL!=f)
  {
    fclose(f);
    f=NULL;
  }
}

void FileLogger::syncBufferToDisk()
{
  openFile(cfg.getFileLoggerFilename());
  if(NULL!=f)
  {
    for(list<string>::iterator i=tmpstrings.begin();i!=tmpstrings.end();i++)
      fprintf(f,"%s\n",i->c_str());
    closeFile();
    tmpstrings.clear();
  }
}

void FileLogger::addMessage(int loglevel,string logmessage)
{
  pthread_mutex_lock(&mutex);
  try
  {
    if(!cfg.getKeepFileLocked())
      tmpstrings.push_back(Utils::rfc2821_date()+": "+logmessage);
    else
    {
      openFile(cfg.getFileLoggerFilename());
      if(NULL!=f)
        fprintf(f,"%s: %s\n",Utils::rfc2821_date().c_str(),logmessage.c_str());
    }
    if(++linecount>30)
    {
      linecount=0;
      if(!cfg.getKeepFileLocked())
        syncBufferToDisk();
      else if(NULL!=f)
        fflush(f);
    }
  }
  catch(Exception &e)
  {
    pthread_mutex_unlock(&mutex);
    throw e;
  }
  pthread_mutex_unlock(&mutex);
}
