// DragonX Wallet - ImGui Edition
// Copyright 2024-2026 The Hush Developers
// Released under the GPLv3

#include "console_model.h"

#include <utility>

namespace dragonx {
namespace ui {

void ConsoleModel::ingest(const std::string& text, ConsoleChannel channel, int foldSpan)
{
    std::lock_guard<std::mutex> lock(ingest_mutex_);
    ConsoleModelLine line;
    line.text = text;
    line.channel = channel;
    line.foldSpan = foldSpan;
    pending_.push_back(std::move(line));
}

ConsoleModel::DrainResult ConsoleModel::drain()
{
    std::vector<ConsoleModelLine> incoming;
    {
        std::lock_guard<std::mutex> lock(ingest_mutex_);
        if (pending_.empty()) return {};
        incoming.swap(pending_);
    }

    DrainResult result;
    result.added = incoming.size();
    for (auto& line : incoming)
        lines_.push_back(std::move(line));

    while (lines_.size() > max_lines_) {
        lines_.pop_front();
        ++result.popped;
    }
    ++revision_;   // deque changed — lets the view memoize its filter/layout passes
    return result;
}

void ConsoleModel::clear()
{
    lines_.clear();
    ++revision_;
}

bool ConsoleModel::toggleCollapsed(std::size_t i)
{
    if (i >= lines_.size() || lines_[i].foldSpan <= 0) return false;
    lines_[i].collapsed = !lines_[i].collapsed;
    ++revision_;   // fold change alters which lines are visible
    return lines_[i].collapsed;
}

} // namespace ui
} // namespace dragonx
