#include "DebugWindowRegistry.hpp"
#include "DebugWindow.hpp"
#include <imgui.h>
#include <algorithm>

namespace tw::dbg {

void DebugWindowRegistry::add(DebugWindow* window) {
    auto remembered = m_open_state.find(window->id());
    if(remembered != m_open_state.end()) {
        window->set_open(remembered->second);
    }

    m_windows.push_back(window);
}

void DebugWindowRegistry::remove(DebugWindow* window) {
    m_open_state[window->id()] = window->is_open();
    std::erase(m_windows, window);
}

void DebugWindowRegistry::draw_menu() {
    if(!ImGui::BeginMenu("Windows")) {
        return;
    }

    // Ordered by the first panel that asked for the category, so the menu does
    // not reshuffle as panels come and go.
    std::vector<std::string> categories;
    for(auto* window : m_windows) {
        if(std::find(categories.begin(), categories.end(), window->category()) == categories.end()) {
            categories.push_back(window->category());
        }
    }

    for(const auto& category : categories) {
        if(!ImGui::BeginMenu(category.c_str())) {
            continue;
        }

        for(auto* window : m_windows) {
            if(window->category() == category) {
                ImGui::MenuItem(window->title().c_str(), nullptr, window->open_flag());
            }
        }

        ImGui::EndMenu();
    }

    ImGui::EndMenu();
}

void DebugWindowRegistry::draw_windows() {
    for(auto* window : m_windows) {
        window->draw();
    }
}

}
