//------------------------------------------------------------------------------
/*
    This file is part of clio: https://github.com/XRPLF/clio
    Copyright (c) 2025, the clio developers.

    Permission to use, copy, modify, and distribute this software for any
    purpose with or without fee is hereby granted, provided that the above
    copyright notice and this permission notice appear in all copies.

    THE  SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
    WITH  REGARD  TO  THIS  SOFTWARE  INCLUDING  ALL  IMPLIED  WARRANTIES  OF
    MERCHANTABILITY  AND  FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
    ANY  SPECIAL,  DIRECT,  INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
    WHATSOEVER  RESULTING  FROM  LOSS  OF USE, DATA OR PROFITS, WHETHER IN AN
    ACTION  OF  CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
    OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
//==============================================================================

#include "util/LoggerFixtures.hpp"

#include "util/log/Logger.hpp"

#include <spdlog/common.h>
#include <spdlog/logger.h>
#include <spdlog/pattern_formatter.h>
#include <spdlog/sinks/ostream_sink.h>
#include <spdlog/spdlog.h>

#include <algorithm>
#include <memory>
#include <string_view>

void
LoggerFixture::init()
{
    util::LogServiceState::init(false, util::Severity::FTL, {});

    std::ranges::for_each(util::Logger::kCHANNELS, [](std::string_view const channel) {
        util::LogService::registerLogger(channel);
    });

    spdlog::set_default_logger(spdlog::get("General"));
}

void
LoggerFixture::resetTestingLoggers()
{
    auto ostreamSink = std::make_shared<spdlog::sinks::ostream_sink_mt>(buffer_.getStream());
    ostreamSink->set_formatter(std::make_unique<spdlog::pattern_formatter>("%^%3!l:%n%$ - %v"));
    ostreamSink->set_level(spdlog::level::trace);
    util::LogServiceState::replaceSinks({ostreamSink});

    spdlog::apply_all([](std::shared_ptr<spdlog::logger> logger) { logger->set_level(spdlog::level::trace); });
    spdlog::get("General")->set_level(spdlog::level::debug);
}

LoggerFixture::LoggerFixture()
{
    util::LogServiceState::reset();
    util::LogServiceState::init(false, util::Severity::TRC, {});

    resetTestingLoggers();
}

LoggerFixture::~LoggerFixture()
{
    util::LogServiceState::replaceSinks({});
    spdlog::apply_all([](std::shared_ptr<spdlog::logger> logger) { logger->set_level(spdlog::level::critical); });
}
