#pragma once

#include <spdlog/spdlog.h>
#include <spdlog/sinks/stdout_color_sinks.h>
#include <spdlog/sinks/rotating_file_sink.h>
#include <memory>

namespace simple_object_storage {

class Logger {
public:
    static void init(const std::string& log_level = "info", 
                     const std::string& log_file = "",
                     size_t max_file_size = 10 * 1024 * 1024,
                     size_t max_files = 3) {
        
        auto console_sink = std::make_shared<spdlog::sinks::stdout_color_sink_mt>();
        console_sink->set_level(spdlog::level::trace);
        
        std::vector<spdlog::sink_ptr> sinks{console_sink};
        
        if (!log_file.empty()) {
            auto file_sink = std::make_shared<spdlog::sinks::rotating_file_sink_mt>(
                log_file, max_file_size, max_files);
            file_sink->set_level(spdlog::level::trace);
            sinks.push_back(file_sink);
        }
        
        auto logger = std::make_shared<spdlog::logger>("sos", sinks.begin(), sinks.end());
        
        if (log_level == "trace") {
            logger->set_level(spdlog::level::trace);
        } else if (log_level == "debug") {
            logger->set_level(spdlog::level::debug);
        } else if (log_level == "info") {
            logger->set_level(spdlog::level::info);
        } else if (log_level == "warn" || log_level == "warning") {
            logger->set_level(spdlog::level::warn);
        } else if (log_level == "error") {
            logger->set_level(spdlog::level::err);
        } else if (log_level == "critical") {
            logger->set_level(spdlog::level::critical);
        } else {
            logger->set_level(spdlog::level::info);
        }
        
        logger->set_pattern("[%Y-%m-%d %H:%M:%S.%e] [%l] [%t] %v");
        
        spdlog::set_default_logger(logger);
        spdlog::flush_every(std::chrono::seconds(3));
    }
    
    static std::shared_ptr<spdlog::logger> get() {
        return spdlog::default_logger();
    }
};

#ifdef LOG_TRACE
#undef LOG_TRACE
#endif
#ifdef LOG_DEBUG
#undef LOG_DEBUG
#endif
#ifdef LOG_INFO
#undef LOG_INFO
#endif
#ifdef LOG_WARN
#undef LOG_WARN
#endif
#ifdef LOG_ERROR
#undef LOG_ERROR
#endif

#define LOG_TRACE(...) SPDLOG_TRACE(__VA_ARGS__)
#define LOG_DEBUG(...) SPDLOG_DEBUG(__VA_ARGS__)
#define LOG_INFO(...) SPDLOG_INFO(__VA_ARGS__)
#define LOG_WARN(...) SPDLOG_WARN(__VA_ARGS__)
#define LOG_ERROR(...) SPDLOG_ERROR(__VA_ARGS__)
#define LOG_CRITICAL(...) SPDLOG_CRITICAL(__VA_ARGS__)

}