#include "console_output_model.h"

#include <algorithm>
#include <cctype>

namespace dragonx {
namespace ui {

namespace {
std::string lowerCopy(std::string value)
{
    std::transform(value.begin(), value.end(), value.begin(),
                   [](unsigned char c) { return static_cast<char>(std::tolower(c)); });
    return value;
}
}

bool consoleLinePassesFilter(const std::string& lineText,
                             ImU32 lineColor,
                             const ConsoleOutputFilter& filter)
{
    if (!filter.daemonMessagesEnabled && lineColor == filter.daemonColor) return false;
    if (!filter.rpcTraceEnabled && lineColor == filter.rpcTraceColor) return false;
    // "[app] ..." lines share COLOR_INFO with other info text, so match them by prefix.
    if (!filter.appMessagesEnabled && lineText.rfind("[app] ", 0) == 0) return false;
    if (filter.errorsOnly && lineColor != filter.errorColor) return false;
    if (!filter.text.empty()) {
        std::string needle = lowerCopy(filter.text);
        std::string haystack = lowerCopy(lineText);
        if (haystack.find(needle) == std::string::npos) return false;
    }
    return true;
}

} // namespace ui
} // namespace dragonx
