/******************************************************************************
*	File		-	worldView.cpp
*	Author		-	Joey Pollack
*	Date		-	2022/01/26 (y/m/d)
*	Mod Date	-	2022/01/26 (y/m/d)
*	Description	-	A rendered view of the world
******************************************************************************/

#include "world_view.h"
#include <core/core.h>
#include <graphics/graphics.h>
#include <assets/types/image.h>
#include <utils/logger.h>
#include <world/world.h>
#include <dearimgui/imgui.h>
#include <editor/editor.h>
#include <gui/panel_manager.h>

namespace lunarium { namespace editor
{
    WorldView::WorldView()
        : Panel("World View", PanelDockZone::DDZ_CENTER, true, ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoScrollbar), mpWorld(nullptr),
            mFrameBuffer(-1), mPrevWidth(0), mPrevHeight(0), mpCanvasImage(nullptr)
    {

    }

    void WorldView::Update(float delta)
    {
        // Need to remake the frame buffer if the window size has changed
        int width, height;
        GetSize(width, height);

        if ((width > 0 && height > 0) && (mPrevWidth != width || mPrevHeight != height))
        {
            mPrevWidth = width; 
            mPrevHeight = height;

            if (mFrameBuffer > -1)
            {
                Core::Graphics().DestroyRenderTexture(mFrameBuffer);
            }

            mFrameBuffer = Core::Graphics().CreateRenderTexture(width, height, 4);
        }

        // TODO: Handle view navigation input

        // Render the current state of the world
        if (mpWorld)
        {
            Core::GetInstance().BeginRenderToTexture(mFrameBuffer).LogIfFailed(Editor::LogCat);
            mpWorld->Render(&Core::Graphics());
            mpCanvasImage = Core::GetInstance().EndRenderToTexture();
        }
    }

    void WorldView::DoFrame()
    { 
        // TODO: Draw toolbar

        // Draw world render
        if (mpCanvasImage)
        {
            ImGui::Image((ImTextureID)mpCanvasImage->GetGLTextureID64(), 
                        ImVec2(mpCanvasImage->GetWidth(), mpCanvasImage->GetHeight()), ImVec2(0, 1), ImVec2(1, 0));
        }
    }
}}