#ifndef FILESERVER_LOGGING_HXX
#define FILESERVER_LOGGING_HXX

#include <cstdarg>
#include <spdlog/spdlog.h>
#include <corvusoft/restbed/logger.hpp>

namespace {
}

namespace logging {
    struct RestbedLogger : public restbed::Logger {
        void stop() override {}
        void start(const std::shared_ptr<const restbed::Settings>&) override {
            logger = spdlog::default_logger()->clone("restbed");
        }
        void log(Level level, const char *format, ...) override {
            std::va_list args;
            va_start(args, format);
            restbed_log(level, format, args);
            va_end(args);
        }
        void log_if(bool expression, Level level, const char *format, ...) override {
            if (expression) {
                va_list args;
                va_start(args, format);
                restbed_log(level, format, args);
                va_end(args);
            }
        }

    private:
        std::shared_ptr<spdlog::logger> logger;
        void restbed_log(const restbed::Logger::Level restbed_level, const char* format, va_list args) {
            spdlog::level::level_enum level;
            switch (restbed_level) {
                case restbed::Logger::DEBUG:   level = spdlog::level::level_enum::debug;    break;
                case restbed::Logger::INFO:    level = spdlog::level::level_enum::info;     break;
                case restbed::Logger::WARNING: level = spdlog::level::level_enum::warn;     break;
                case restbed::Logger::ERROR:   level = spdlog::level::level_enum::err;      break;
                case restbed::Logger::SECURITY:
                case restbed::Logger::FATAL:   level = spdlog::level::level_enum::critical; break;
            }
            std::string buf;
            buf.resize(1024);
            int written = vsnprintf(buf.data(), 1024, format, args);
            //if (std::string_view{buf.cbegin(), buf.cbegin()+10} == "Incoming '")
            //    return;
            if (written >= 1024) {
                buf.resize(written + 10);
                written = vsnprintf(buf.data(), written + 10, format, args);
            }
            buf.resize(written);
            logger->log(level, buf);
        }
    };
}


#endif //FILESERVER_LOGGING_HXX
