// %pacpus:license{
// This file is part of the PACPUS framework distributed under the
// CECILL-C License, Version 1.0.
// %pacpus:license}
/// @version    $Id: Log.cpp 76 2013-01-10 17:05:10Z kurdejma $

#include <Pacpus/kernel/Log.h>

#ifdef PACPUS_USE_LOG

#include <boost/log/detail/date_time_format_parser.hpp>
#include <boost/log/expressions.hpp>
#include <boost/log/sinks/text_file_backend.hpp>
#include <boost/log/sinks/text_ostream_backend.hpp>
#include <boost/log/sources/severity_logger.hpp>
#include <boost/log/sources/record_ostream.hpp>
#include <boost/log/support/date_time.hpp>
#include <boost/log/utility/setup/common_attributes.hpp>
#include <boost/log/utility/setup/file.hpp>
#include <boost/log/utility/setup/formatter_parser.hpp>
#include <boost/log/utility/empty_deleter.hpp>
#include <ostream>
#include <QString>

template< typename CharT, typename TraitsT >
std::basic_ostream< CharT, TraitsT >& operator<< (std::basic_ostream< CharT, TraitsT >& strm, QString const& s)
{
    strm << s.toStdString();
    return strm;
}

// explicit instantiation
template
PACPUSLIB_API std::basic_ostream<char>& operator<< (std::basic_ostream<char>& strm, QString const& s);

namespace pacpus {
   
void init_log_factories()
{
    boost::log::register_simple_formatter_factory< QString, char >("QString");
}

static int niftyCounter;

LogConfigurator::LogConfigurator()
{
    if (0 == niftyCounter++) {
        LOG_INFO("LogConfigurator constructor");
        init_log_factories();
    }
}

LogConfigurator::~LogConfigurator()
{
    if (0 == --niftyCounter) {
        // clean up
        LOG_INFO("LogConfigurator destructor");
    }
}

void LogConfigurator::configureLoggerWithFile(const char * logFileName)
{
    using namespace boost;

    namespace logging = boost::log;
    namespace sinks = boost::log::sinks;
    namespace src = boost::log::sources;
    namespace expr = boost::log::expressions;
    namespace attrs = boost::log::attributes;
    namespace keywords = boost::log::keywords;
    
    logging::add_common_attributes();
    logging::core::get()->set_filter
    (
#ifdef NDEBUG
        // release
        logging::trivial::severity >= logging::trivial::debug
#else
        // debug
        logging::trivial::severity >= logging::trivial::trace
#endif
    );

    // Add a file log
    logging::add_file_log
    (
        keywords::file_name = logFileName,
        keywords::rotation_size = 10 * 1024 * 1024,
        keywords::time_based_rotation = sinks::file::rotation_at_time_point(0, 0, 0),
        //keywords::format = "%LineID% [%TimeStamp%]: %Message%"
        keywords::format =
        (
            expr::stream
                << std::setfill('0') << std::setw(6) << expr::attr< unsigned int >("LineID")
                //<< " [" << expr::format_date_time< posix_time::ptime >("TimeStamp", date_time::iso_extended_format) << "] "
                << " [" << expr::format_date_time< posix_time::ptime >("TimeStamp", "%Y-%m-%d %T.%f") << "] "
                << "<" << logging::trivial::severity << ">"
                << " "
                << expr::smessage
        )
    );

    // Create a backend and attach a couple of streams to it
    boost::shared_ptr< sinks::text_ostream_backend > backend =
        make_shared< sinks::text_ostream_backend >();
    backend->add_stream(
        shared_ptr< std::ostream >(&std::clog, logging::empty_deleter())
    );

    // Enable auto-flushing after each log record written
    backend->auto_flush(true);

    // Wrap it into the frontend and register in the core.
    // The backend requires synchronization in the frontend.
    typedef sinks::synchronous_sink< sinks::text_ostream_backend > sink_t;
    shared_ptr< sink_t > sink(new sink_t(backend));
    sink->set_filter
    (
        logging::trivial::severity >= logging::trivial::info
    );

    sink->set_formatter
    (
        expr::stream
            << std::setfill('0') << std::setw(6) << expr::attr< unsigned int >("LineID")
            //<< " [" << expr::format_date_time< posix_time::ptime >("TimeStamp", date_time::iso_extended_format) << "] "
            << " [" << expr::format_date_time< posix_time::ptime >("TimeStamp", "%Y-%m-%d %T.%f") << "] "
            << "<" << logging::trivial::severity << ">"
            << " "
            << expr::smessage
    );

    logging::core::get()->add_sink(sink);

    LOG_INFO("logger initialised");
}

} // namespace pacpus

#else // PACPUS_USE_LOG

namespace pacpus

    LogConfigurator::LogConfigurator()
    {}
    void LogConfigurator::configureLoggerWithFile(const char * /*configFilename*/)
    {}

} // namespace pacpus

#endif // PACPUS_USE_LOG
