#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"

#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(DrawingContext* context)
    :   AbstractPainter(context),
        mMeshPainter(std::make_unique<OpenGlMeshPainter>()),
        mTextPainter(std::make_unique<OpenGlTextPainter>())
{

}

void OpenGlPainter::paint()
{
    auto surface = mDrawingContext->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 = mDrawingContext->getSurface()->getScene();
    for (const auto item : scene->getItems())
    {
        if (item->getType() == SceneItem::Type::MODEL)
        {
            mMeshPainter->paint(dynamic_cast<SceneModel*>(item), mDrawingContext);
        }
        else if (item->getType() == SceneItem::Type::TEXT)
        {
            mTextPainter->paint(dynamic_cast<SceneText*>(item), mDrawingContext);
        }
    }

    glFlush();
}
