/** \file
 *
 *  Contains the TextLogWriter class implementation.
 *
 *  Copyright (c) 2007,2008,2009 MBARI
 *  MBARI Proprietary Information.  All Rights Reserved
 *
 */

#include "TextLogWriter.h"

#include "io/OutStream.h"
#include "logger/DirectoryEntry.h"

/** Default Constructor
 * Assumes that the stream will be assigned later via setOutStream()
 *
 * \param withDirectory If true, include DirectoryEntry entries.
 */
TextLogWriter::TextLogWriter( bool withDirectory )
    : LogWriter(),
      withDirectory_( withDirectory )
{}

/** Constructor, takes an OutStream.
 *
 * \param stream An OutStream for output.
 * \param withDirectory If true, include DirectoryEntry entries.
 */
TextLogWriter::TextLogWriter( OutStream &stream, bool withDirectory )
    : LogWriter( stream ),
      withDirectory_( withDirectory )
{}

/// Destructor
TextLogWriter::~TextLogWriter()
{}

/// Start the text log
unsigned int TextLogWriter::writeHeader()
{
    unsigned int bytesWritten( 0 );

    if( withDirectory_ && NULL != logStream_ && logStream_->isWritable() )
    {
        Timestamp timeBase;
        bytesWritten += DirectoryEntry().write( timeBase, *logStream_ );
    }

    return bytesWritten;
}

/// Write the given Entry to the OutStream.
///
/// Pipes the toString() method of the entry to the OutStream with
/// some formatting.
unsigned int TextLogWriter::write( const LogEntry *entry, const Unit* unit )
{
    // Should check for valid OutStream, eh?
    if( isValid() )
    {
        MutexLocker lock( writeMutex_ );

        if( entry != NULL )
        {

            // Want to append date, etc here...
            Str output = entry->toString( unit );
            if( output.length() > 0 )
            {
                logStream_->write( output.cStr() );
                logStream_->writeChar( '\n' );
            }
            // Need to get character count...
            return output.length() + 1;
        }
    }

    /// Or else what?
    return 0;

}

