/*
 * 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_IO_H
  #include <io.h>
#endif
#ifdef TANGO_HAVE_UNISTD_H
  #include <unistd.h>
#endif
#include <tango/common/log4tango/FileAppender.h>

#include <fcntl.h>

namespace log4tango
{

#ifdef _MSC_VER
  #pragma warning(push)
  #pragma warning(disable : 4996) // non compliant POSIX names (close for _close, ...)
#endif

FileAppender::FileAppender(const std::string &name, const std::string &file_name, bool append, mode_t mode) :
    LayoutAppender(name),
    _file_name(file_name),
    _flags(O_CREAT | O_APPEND | O_WRONLY),
    _mode(mode)
{
    if(!append)
    {
        _flags |= O_TRUNC;
    }
    _fd = ::open(_file_name.c_str(), _flags, _mode);
}

FileAppender::FileAppender(const std::string &name, int fd) :
    LayoutAppender(name),

    _fd(fd),
    _flags(O_CREAT | O_APPEND | O_WRONLY),
    _mode(00644)
{
    // no-op
}

FileAppender::~FileAppender()
{
    close();
}

void FileAppender::close()
{
    if(_fd != -1)
    {
        ::close(_fd);
        _fd = -1;
    }
}

bool FileAppender::is_valid() const
{
    return _fd >= 0;
}

void FileAppender::set_append(bool append)
{
    if(append)
    {
        _flags &= ~O_TRUNC;
    }
    else
    {
        _flags |= O_TRUNC;
    }
}

bool FileAppender::get_append() const
{
    return (_flags & O_TRUNC) == 0;
}

void FileAppender::set_mode(mode_t mode)
{
    _mode = mode;
}

mode_t FileAppender::get_mode() const
{
    return _mode;
}

int FileAppender::_append(const LoggingEvent &event)
{
    std::string message(get_layout().format(event));
    // Messages longer than sizeof(uint) will be truncated.
    if(::write(_fd, message.data(), static_cast<unsigned int>(message.length())) == 0)
    {
        return -1;
    }
    return 0;
}

bool FileAppender::reopen()
{
    if(_file_name != "")
    {
        int fd = ::open(_file_name.c_str(), _flags, _mode);
        if(fd < 0)
        {
            return false;
        }
        else
        {
            if(_fd != -1)
            {
                ::close(_fd);
            }
            _fd = fd;
        }
    }
    return true;
}

#ifdef _MSC_VER
  #pragma warning(pop)
#endif
} // namespace log4tango
