/*!
  @header ECFileLoggingWriter
  @abstract Module of Encore
 
  @availability OS X, GNUstep
  @copyright 2004, 2005, 2006 Oliver Langer

  Author: Oliver Langer

  This library is free software; you can redistribute it and/or
  modify it under the terms of the GNU Lesser General Public
  License as published by the Free Software Foundation; either
  version 2.1 of the License, or (at your option) any later version.

  This library 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
  Lesser General Public License for more details.

  You should have received a copy of the GNU Lesser General Public
  License along with this library; if not, write to the Free Software
  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301 USA

  <pre>
  -------------------------------------------------------------------------
  Modification history

  03.02.06 ola     initial version
  22.08.06 ola     license changed
  -------------------------------------------------------------------------
  </pre>
*/

#include <Encore/ECFileLoggingWriter.h>
#include <Encore/ECExceptions.h>

@implementation ECFileLoggingWriter

- init {
  self = [super init];

  self->logBaseFilename = nil;
  self->logBackupFilenameSuffix = [[NSString alloc] 
    initWithString: ECFileLoggingWriter_DEFAULT_BACKUSUFFIX];
  self->maxFilesize = ECFileLoggingWriter_DEFAULT_MAXFILESIZE;
  self->lock = [[NSLock alloc] init];
  self->fileHandle = nil;
  self->encoding = NSASCIIStringEncoding;
  
  return self;
}


- (void) dealloc {
  [self->logBaseFilename release];
  [self->logBackupFilenameSuffix release];
  [self->lock release];
  [self->fileHandle release];
  
  [super dealloc];
}


- checkFilestatus {
  /* check for log rotation: */
  if( nil != self->fileHandle ) {
    if( [self->fileHandle offsetInFile] > maxFilesize ) {
      [self closeAndMoveFile];
    } 
  }
  
  /* check for file opening/creation: */
  if( nil == self->fileHandle ) {
    [self openFile];
  }

  return self;
}


- closeAndMoveFile {
  NSString *backupFilename;
  
  [self->fileHandle closeFile];
  self->fileHandle = nil;
  backupFilename = [self createBackupFilename];
  if( ![[NSFileManager defaultManager]
    movePath: self->logBaseFilename
    toPath: backupFilename
    handler:nil] ) {
    [[[ECIllegalStateException alloc]
      initWithIllegalStateInfo: 
        [NSString stringWithFormat:
          @"ECFileLoggingWriter::closeAndMoveFile:"\
          " Unable to move logging file %@ to %@!", self->logBaseFilename,
            backupFilename]]
      raise];
  }
  return self;
}


- (NSString *) createBackupFilename {
  NSString *backupFilename;
  unsigned int counter = 0;
  NSString *toReturn = nil;
  
  /* crate suffix */
  backupFilename = [[NSDate date] 
    descriptionWithCalendarFormat: self->logBackupFilenameSuffix
    timeZone: nil
    locale: nil];
  
  /* create full file name by adding prefix: */
  backupFilename = [NSString stringWithFormat: @"%@.%@",
    self->logBaseFilename, backupFilename];
  
  toReturn = backupFilename;
  while( [[NSFileManager defaultManager]
    fileExistsAtPath: toReturn] ) {
    
    toReturn = [NSString 
      stringWithFormat: @"%@-%u", backupFilename, counter++];
  }
  
  return toReturn;
}


- openFile {
  /* open or create file: */
  if( ![[NSFileManager defaultManager] 
    fileExistsAtPath: self->logBaseFilename] ) {
    /* create file */
    if( ![[NSFileManager defaultManager]
          createFileAtPath: self->logBaseFilename
          contents: nil
          attributes: nil] ) {
      [[[ECIllegalStateException alloc]
        initWithIllegalStateInfo: 
          [NSString stringWithFormat: @"ECSimpleFileLogWriter::"\
            "checkFilestatus: Unable to create file with name=%@"]
      ] raise];
    }
  }
  
  /* open file: */
  self->fileHandle = [[NSFileHandle 
    fileHandleForUpdatingAtPath: self->logBaseFilename] retain];
  if( nil == self->fileHandle ) {
    [[[ECIllegalStateException alloc]
      initWithIllegalStateInfo: 
        [NSString stringWithFormat: @"ECSimpleFileLogWriter::"\
          "checkFilestatus: Unable to create file with name=%@",
          self->logBaseFilename]
      ] raise];
  }
    
  [self->fileHandle seekToEndOfFile];
  
  return self;
}


- setEncoding: (NSStringEncoding) anEncoding {
  self->encoding = anEncoding;

  return self;
}


- setBaseFilename: (NSString *) aBaseFilename {
  id tmp;
  tmp = self->logBaseFilename;
  self->logBaseFilename = [aBaseFilename retain];
  [tmp release];

  return self;
}


- setBackupFilenameSuffix: (NSString *) aBackupname {
  id tmp = self->logBackupFilenameSuffix;
  self->logBackupFilenameSuffix = [aBackupname retain];
  [tmp release];

  return self;
}


- setMaxFilesize: (unsigned int) nrBytes {
  self->maxFilesize = nrBytes;

  return self;
}


- writeLog: (NSString *) logEntry {
  [self->lock lock];
  NS_DURING
    [self checkFilestatus];
    [self->fileHandle writeData: 
      [logEntry dataUsingEncoding: self->encoding]];
  NS_HANDLER
    [self->lock unlock];
    [localException raise];
  NS_ENDHANDLER

  [self->lock unlock];
  return self;
}

@end

