#include "tile/base/logging/basic_file_sink.h"

namespace tile {
BasicFileSink::Ptr
BasicFileSink::Create(const std::string &filepath)
{
    auto sink = std::shared_ptr<BasicFileSink>(new BasicFileSink());
    sink->set_filepath(filepath);
    return sink;
}

BasicFileSink::BasicFileSink() {}

BasicFileSink::~BasicFileSink() {}

void
BasicFileSink::Send(LogSeverity severity,
                    const char *full_filename,
                    const char *base_filename,
                    int line,
                    const LogMessageTime &logmsgtime,
                    const char *message,
                    size_t message_len)
{
    TILE_CHECK(!filepath_.empty(), "filepath is empty");
    auto msg = ToString(severity, full_filename, base_filename, line, logmsgtime, message, message_len);
    if (!msg.empty() && msg.back() != '\n') { msg.push_back('\n'); }
    ofs_ << std::string(message, message_len) << std::endl;
}

std::string
BasicFileSink::filepath() const
{
    return filepath_;
}

void
BasicFileSink::set_filepath(const std::string &filepath)
{
    filepath_ = filepath;
    ofs_.open(filepath, std::ios::out | std::ios::app);
}

void
BasicFileSink::Flush()
{
    ofs_.flush();
}
}// namespace tile
