#include "common_header.h"
#include "openGLControl.h"

COpenGLControl::COpenGLControl()
{
}

bool COpenGLControl::initOpenGL(HWND hWnd, bool (*initScene)(), void (*renderScene)(), void (*resizeScene)(int, int), void(*releaseScene)())
{
	this->hWnd = hWnd;

	bool Error = false;

	hDC = GetDC(hWnd);

	if(hDC == NULL)
	{
		Error = true;
	}

	PIXELFORMATDESCRIPTOR pfd;

	memset(&pfd, 0, sizeof(PIXELFORMATDESCRIPTOR));

	pfd.nSize = sizeof(PIXELFORMATDESCRIPTOR);
	pfd.nVersion = 1;
	pfd.dwFlags = PFD_DOUBLEBUFFER | PFD_SUPPORT_OPENGL | PFD_DRAW_TO_WINDOW;
	pfd.iPixelType = PFD_TYPE_RGBA;
	pfd.cColorBits = 32;
	pfd.cDepthBits = 24;
	pfd.iLayerType = PFD_MAIN_PLANE;
 
	int PixelFormat = ChoosePixelFormat(hDC, &pfd);

	if(PixelFormat == 0)
	{
		Error = true;
	}

	if(SetPixelFormat(hDC, PixelFormat, &pfd) == FALSE)
	{
		Error = true;
	}

	hRC = wglCreateContext(hDC);

	if(hRC == NULL)
	{
		Error = true;
	}

	if(wglMakeCurrent(hDC, hRC) == FALSE)
	{
		Error = true;
	}

	if(glewInit() != GLEW_OK)
	{
		Error = true;
	}

	if(WGLEW_ARB_create_context)
	{
		wglDeleteContext(hRC);

		int iContextAttribs[] =
		{
			WGL_CONTEXT_MAJOR_VERSION_ARB, 3,
			WGL_CONTEXT_MINOR_VERSION_ARB, 3,
			WGL_CONTEXT_FLAGS_ARB, WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB,
			0
		};

		hRC = wglCreateContextAttribsARB(hDC, 0, iContextAttribs);

		if(hRC == NULL)
		{
			Error = true;
		}

		if(wglMakeCurrent(hDC, hRC) == FALSE)
		{
			Error = true;
		}
	}
	else
	{
		Error = true;
	}

	if(Error)
	{
		MessageBox(NULL, "initOpenGL failed!", "Error", MB_OK | MB_ICONERROR);
		return false;
	}

	this->initScene = initScene;
	this->renderScene = renderScene;
	this->resizeScene = resizeScene;
	this->releaseScene = releaseScene;

	if(WGLEW_EXT_swap_control)
	{
		wglSwapIntervalEXT(0);
	}

	if(initScene != NULL)
	{
		return initScene();
	}

	return true;
}

void COpenGLControl::render()
{
	if(renderScene != NULL)
	{
		renderScene();
	}

	SwapBuffers(hDC);
}

void COpenGLControl::resize(int Width, int Height)
{
	if(resizeScene != NULL)
	{
		resizeScene(Width, Height);
	}
}

void COpenGLControl::releaseOpenGLControl()
{
	if(releaseScene != NULL && GLEW_VERSION_3_3)
	{
		releaseScene();
	}

	wglDeleteContext(hRC);
}
