#include "OpenGlPainter.h"

#include "DrawingContext.h"
#include "DrawingSurface.h"
#include "Scene.h"
#include "SceneItem.h"
#include "SceneModel.h"
#include "SceneText.h"

#include "TriMesh.h"

#include "FontsManager.h"
#include "FontGlyph.h"
#include "TextData.h"

#include "OpenGlShaderProgram.h"
#include "OpenGlMeshPainter.h"
#include "OpenGlTextPainter.h"
#include "OpenGlFontTexture.h"

#include "File.h"

#ifdef _WIN32
#include <windows.h>
#endif

#define GL_GLEXT_PROTOTYPES
#include <GL/gl.h>
#include <GL/glu.h>
#include <GL/glx.h>

#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>

#include <iostream>

OpenGlPainter::OpenGlPainter()
    : mMeshPainter(std::make_unique<OpenGlMeshPainter>()),
      mTextPainter(std::make_unique<OpenGlTextPainter>())
{

}

void OpenGlPainter::paint(DrawingContext* context)
{
    auto surface = context->getSurface();
    const auto width = double(surface->getWidth());
    const auto height = double(surface->getHeight());

    glViewport(0, 0, width, height);
    glOrtho(0, width, 0, height, -1.0, 1.0);

    glClearColor(0.5, 0.5, 1.0, 0.0);
    glClear(GL_COLOR_BUFFER_BIT);

    auto scene = context->getSurface()->getScene();
    for(unsigned idx=0; idx<scene->getNumItems(); idx++)
    {
        auto scene_item = scene->getItem(idx);
        if (scene_item->getType() == SceneItem::Type::MODEL)
        {
            mMeshPainter->paint(dynamic_cast<SceneModel*>(scene_item), context);
        }
        else if (scene_item->getType() == SceneItem::Type::TEXT)
        {
            mTextPainter->paint(dynamic_cast<SceneText*>(scene_item), context);
        }
    }

    glFlush();
}
