/*
 * SPDX-FileCopyrightText: 2000-2002 Copyright LifeLine Networks BV (www.lifeline.nl)
 * SPDX-FileCopyrightText: 2000-2002 Copyright Bastiaan Bakker
 * SPDX-FileCopyrightText: 2004 Copyright contributors to the cppTango project
 *
 * SPDX-License-Identifier: LGPL-3.0-or-later
 */

#include <tango/common/log4tango/Portability.h>

#ifdef TANGO_HAVE_UNISTD_H
  #include <unistd.h>
#endif

#include <tango/common/log4tango/Logger.h>
#include <tango/common/log4tango/LoggerStream.h>

namespace log4tango
{

namespace
{
constexpr LoggerStream::SourceLocation DefaultSourceLocation{"(unknown)", 0};
}

LoggerStream::LoggerStream(Logger &logger, Level::Value level, bool filter) :
    _logger(logger),
    _level(level),
    _filter(filter),
    _buffer(new std::ostringstream),
    _source_location(DefaultSourceLocation)
{
}

LoggerStream::~LoggerStream()
{
    flush();
    if(_buffer != nullptr)
    {
        delete _buffer;
        _buffer = nullptr;
    }
}

LoggerStream::LoggerStream(LoggerStream &&other) :
    _logger(other._logger),
    _level(other._level),
    _filter(other._filter),
    _buffer(other._buffer),
    _source_location(other._source_location)
{
    other._buffer = nullptr;
}

void LoggerStream::flush()
{
    if((_buffer != nullptr) && _buffer->tellp() > 0)
    {
        if(_filter)
        {
            _logger.log(_source_location.file, _source_location.line, _level, _buffer->str());
        }
        else
        {
            _logger.log_unconditionally(_source_location.file, _source_location.line, _level, _buffer->str());
        }
        _buffer->str("");
        _source_location = DefaultSourceLocation;
    }
}

} // namespace log4tango
