#include "viewport.h"
#include <raylib.h>
#include <imgui.h>
#include <rlImGui.h>

extern Camera camera;
RenderTexture viewport;
RenderTexture new_viewport;
bool swap_viewport = false;

void InitViewport() {
    viewport = LoadRenderTexture(800, 600);
}

void UpdateViewport() {
    if(swap_viewport) {
        UnloadRenderTexture(viewport);
        viewport = new_viewport;
        swap_viewport = false;
    }
}

void BeginViewport() {
    BeginTextureMode(viewport);
}

void EndViewport() {
    EndTextureMode();
}

void RenderViewport() {
    ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, (ImVec2){0.0f, 0.0f});
    
    ImGui::Begin("Viewport", NULL, ImGuiWindowFlags_NoScrollbar);
    {
        if(ImGui::IsWindowHovered()) {
            if(IsMouseButtonDown(MOUSE_BUTTON_RIGHT)) {
                if(!IsCursorHidden())
                    DisableCursor();
                UpdateCamera(&camera, CAMERA_FREE);
            } else {
                if(IsCursorHidden())
                    EnableCursor();
            }
        } else {
            if(IsCursorHidden())
                EnableCursor();
        }

        ImVec2 area = ImGui::GetContentRegionAvail(); 

        if(viewport.texture.width != area.x || viewport.texture.height != area.y) {
            new_viewport = LoadRenderTexture(area.x, area.y);
            swap_viewport = true;
        }

        rlImGuiImageRenderTexture(&viewport);  
    }
    ImGui::End();
    
    ImGui::PopStyleVar();
}
