#include "viewport.h"
#include <raylib.h>
#include <rlcimgui.h>
#include <imgui_impl_raylib.h>
#include <stddef.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() {
    igPushStyleVar_Vec2(ImGuiStyleVar_WindowPadding, (ImVec2){0.0f, 0.0f});
    
    igBegin("Viewport", NULL, ImGuiWindowFlags_NoScrollbar);
    {
        if(igIsWindowHovered(0)) {
            if(IsMouseButtonDown(MOUSE_BUTTON_RIGHT)) {
                if(!IsCursorHidden())
                    DisableCursor();
                UpdateCamera(&camera, CAMERA_FREE);
            } else {
                if(IsCursorHidden())
                    EnableCursor();
            }
        } else {
            if(IsCursorHidden())
                EnableCursor();
        }

        ImVec2 area;
        igGetContentRegionAvail(&area); 

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

        rligImageRenderTexture(&viewport);  
    }
    igEnd();
    
    igPopStyleVar(1);
}
