/*
	GameEngine and Editor
	by John Ryland
	Copyright (c) 2023
*/

////////////////////////////////////////////////////////////////////////////////////
//	Flat Entity List View

#include "FlatEntityListView.h"
#include "imgui.h"
#include "imgui_internal.h"
#include <algorithm>

namespace GameEngine {

void FlatEntityListView::AddShowMenuItem()
{
    ImGui::MenuItem("Show Entity List", NULL, &m_open);
}

void FlatEntityListView::Initialize()
{
}

void FlatEntityListView::Shutdown()
{
}

void FlatEntityListView::Update()
{
    if (m_wasOpen != m_open)
        OnVisibilityChanged(m_open);
    m_wasOpen = m_open;
    if (!m_open)
        return;
    if (ImGui::Begin("Entity List", &m_open /*, ImGuiWindowFlags_MenuBar */))
        OnDraw();
    ImGui::End();
}

void FlatEntityListView::OnVisibilityChanged(bool shown)
{
    if (shown)
        OnOpen();
    else
        OnClose();
}

void FlatEntityListView::OnOpen()
{
    printf("opened\n");
}

void FlatEntityListView::OnClose()
{
    printf("closed\n");
}

void FlatEntityListView::OnDraw()
{
    // Alternating light/dark background lines
    float x1 = ImGui::GetCurrentWindow()->WorkRect.Min.x;
    float x2 = ImGui::GetCurrentWindow()->WorkRect.Max.x;
    float line_height = ImGui::GetTextLineHeight() + ImGui::GetStyle().ItemSpacing.y;
    float y0 = ImGui::GetCursorScreenPos().y + (float)(int)(-ImGui::GetStyle().ItemSpacing.y * 0.5f);
    int row_display_start, row_display_end;
    //ImGui::CalcListClipping(50, line_height, &row_display_start, &row_display_end);
    float y = y0 + (line_height * row_display_start);
    for (int row_n = row_display_start; row_n < row_display_end; row_n+=2, y += (2 * line_height))
        ImGui::GetWindowDrawList()->AddRectFilled(ImVec2(x1, y), ImVec2(x2, y + line_height), ImGui::GetColorU32(ImVec4(0.2f, 0.2f, 0.2f, 0.5f)));


    auto entityNames = m_entityComponentSystem.AllEntities();
    std::sort(entityNames.begin(), entityNames.end());
    for (int n = 0; n < entityNames.size(); n++)
    {
        auto entityId = entityNames[n];
        auto entName = "entity #" + std::to_string(entityId);
        // folder F07B  open folder F07C  globe F0AC   terminal F120   up F106 down F107  disk F1C0  layers F5FD  box F466     empty file F15B  file F15C  
        if (ImGui::TreeNode(entName.c_str()))
        {
            auto comps = m_entityComponentSystem.EntityComponents(entityId);
            for (auto& comp : comps)
                if (ImGui::TreeNodeEx(comp.c_str(), ImGuiTreeNodeFlags_Leaf))
                    ImGui::TreePop();
            ImGui::TreePop();
        }
    }
}

} // GameEngine namespace
