#include "XcbGlWindowInterface.h"

#include "XcbGlInterface.h"
#include "FileLogger.h"
#include <iostream>

#include <GL/gl.h>

XcbGlWindowInterface::XcbGlWindowInterface(XcbGlInterface* glInterface)
    :   mGlInterface(glInterface),
        mDrawable(),
        mWindow()
{

}

XcbGlWindowInterface::~XcbGlWindowInterface()
{
    if (mWindow)
    {
        destroyWindow();
    }
}

void XcbGlWindowInterface::afterPaint()
{
    swapBuffers();
}

void XcbGlWindowInterface::swapBuffers()
{
    glXSwapBuffers(mGlInterface->getDisplay(), mDrawable);
}

bool XcbGlWindowInterface::initialize(xcb_window_t window)
{
    if (mWindow)
    {
        return true;
    }

    /* Create GLX Window */
    mWindow = glXCreateWindow(mGlInterface->getDisplay(), mGlInterface->getConfig(), window, 0);
    if (!mWindow)
    {
        MLOG_ERROR("glXCreateWindow failed");
        return false;
    }
    mDrawable = mWindow;

    /* make OpenGL context current */
    if (!glXMakeContextCurrent(mGlInterface->getDisplay(), mDrawable, mDrawable, mGlInterface->getContext()))
    {
        MLOG_ERROR("glXMakeContextCurrent failed");
        return false;
    }

    if (auto context = glXGetCurrentContext())
    {
        MLOG_INFO("Has valid GL context");
    }
    else
    {
        MLOG_INFO("No valid GL context");
    }

    int major_version{0};
    int minor_version{0};
    glGetIntegerv(GL_MAJOR_VERSION, &major_version);
    glGetIntegerv(GL_MINOR_VERSION, &minor_version);
    MLOG_INFO("Using opengl version " << major_version << "|" << minor_version);

    return true;
}

void XcbGlWindowInterface::resizeViewPort(unsigned width, unsigned height)
{
    //glViewport(0, 0, width, height);
    //glScissor(0, 0, width, height);

    //glOrtho(0, width, 0, height, -1.0, 1.0);
    //glMatrixMode(GL_PROJECTION);
    //glLoadIdentity();

    //glMatrixMode(GL_MODELVIEW);

}

void XcbGlWindowInterface::destroyWindow()
{
    glXDestroyWindow(mGlInterface->getDisplay(), mWindow);
}
