/*
PolyGun

Copyright (c) 2023 mrkubax10 <mrkubax10@onet.pl>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/

#include "game/renderer/gl/win32_gl_context.hpp"

#include "game/window/win32_window.hpp"
#include "game/renderer/gl/opengl.hpp"
#include "common/logger.hpp"

using namespace polygun::renderer;

Win32GLContext::Win32GLContext(window::Window* window):
	m_context()
{
	window::Win32Window* wnd = static_cast<window::Win32Window*>(window);
	initialize(wnd->get_ctx());
}

Win32GLContext::~Win32GLContext() {
	wglMakeCurrent(nullptr, nullptr);
	wglDeleteContext(m_context);
}

#if defined(RENDERER_GL)
void* Win32GLContext::get_proc_address(const std::string& name) {
	return reinterpret_cast<void*>(wglGetProcAddress(name.c_str()));
}
#endif

bool Win32GLContext::initialize(HDC ctx) {
	PIXELFORMATDESCRIPTOR pixel_format = {0};
	pixel_format.nVersion = 1;
	pixel_format.dwFlags = PFD_DRAW_TO_WINDOW|PFD_SUPPORT_OPENGL|PFD_DOUBLEBUFFER;
	pixel_format.iPixelType = PFD_TYPE_RGBA;
	pixel_format.cColorBits = 32;
	pixel_format.cAlphaBits = 8;
	pixel_format.cDepthBits = 24;
	int pixel_format_id = ChoosePixelFormat(ctx, &pixel_format);
	if(!pixel_format_id)
		LOG_FATAL("Failed to choose pixel format (error code: %d)", GetLastError());
	if(!SetPixelFormat(ctx, pixel_format_id, &pixel_format))
		LOG_FATAL("Failed to set pixel format (error code: %d)", GetLastError());

	m_context = wglCreateContext(ctx);
	if(!m_context)
		LOG_FATAL("Failed to create OpenGL context (error code: %d)", GetLastError());
	if(!wglMakeCurrent(ctx, m_context))
		LOG_FATAL("Failed to make OpenGL context current (error code: %d)", GetLastError());

	return true;
}
