/*
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/window/win32_window.hpp"

#include <array>
#include <locale>
#include <codecvt>

#include "common/logger.hpp"
#include "game/window/keyboard.hpp"

using namespace polygun::window;

static HINSTANCE g_instance;
static std::atomic<Win32Window*> g_current_window = nullptr;
static const std::array g_virtual_keycode_to_keycode = {
	KeyCode::KEY_NONE,
	KeyCode::KEY_NONE,
	KeyCode::KEY_NONE,
	KeyCode::KEY_NONE,
	KeyCode::KEY_NONE,
	KeyCode::KEY_NONE,
	KeyCode::KEY_NONE,
	KeyCode::KEY_NONE,
	KeyCode::KEY_BACKSPACE,
	KeyCode::KEY_TAB,
	KeyCode::KEY_NONE,
	KeyCode::KEY_NONE,
	KeyCode::KEY_NONE,
	KeyCode::KEY_RETURN,
	KeyCode::KEY_NONE,
	KeyCode::KEY_NONE,
	KeyCode::KEY_LEFT_SHIFT,
	KeyCode::KEY_LEFT_CONTROL,
	KeyCode::KEY_LEFT_ALT,
	KeyCode::KEY_PAUSE,
	KeyCode::KEY_CAPS_LOCK,
	KeyCode::KEY_NONE,
	KeyCode::KEY_NONE,
	KeyCode::KEY_NONE,
	KeyCode::KEY_NONE,
	KeyCode::KEY_NONE,
	KeyCode::KEY_NONE,
	KeyCode::KEY_ESCAPE,
	KeyCode::KEY_NONE,
	KeyCode::KEY_NONE,
	KeyCode::KEY_NONE,
	KeyCode::KEY_NONE,
	KeyCode::KEY_SPACE,
	KeyCode::KEY_PAGE_UP,
	KeyCode::KEY_PAGE_DOWN,
	KeyCode::KEY_END,
	KeyCode::KEY_HOME,
	KeyCode::KEY_LEFT,
	KeyCode::KEY_UP,
	KeyCode::KEY_RIGHT,
	KeyCode::KEY_DOWN,
	KeyCode::KEY_NONE,
	KeyCode::KEY_NONE,
	KeyCode::KEY_NONE,
	KeyCode::KEY_PRINT_SCREEN,
	KeyCode::KEY_INSERT,
	KeyCode::KEY_DELETE,
	KeyCode::KEY_NONE,
	KeyCode::KEY_0,
	KeyCode::KEY_1,
	KeyCode::KEY_2,
	KeyCode::KEY_3,
	KeyCode::KEY_4,
	KeyCode::KEY_5,
	KeyCode::KEY_6,
	KeyCode::KEY_7,
	KeyCode::KEY_8,
	KeyCode::KEY_9,
	KeyCode::KEY_NONE,
	KeyCode::KEY_NONE,
	KeyCode::KEY_NONE,
	KeyCode::KEY_NONE,
	KeyCode::KEY_NONE,
	KeyCode::KEY_NONE,
	KeyCode::KEY_NONE,
	KeyCode::KEY_A,
	KeyCode::KEY_B,
	KeyCode::KEY_C,
	KeyCode::KEY_D,
	KeyCode::KEY_E,
	KeyCode::KEY_F,
	KeyCode::KEY_G,
	KeyCode::KEY_H,
	KeyCode::KEY_I,
	KeyCode::KEY_J,
	KeyCode::KEY_K,
	KeyCode::KEY_L,
	KeyCode::KEY_M,
	KeyCode::KEY_N,
	KeyCode::KEY_O,
	KeyCode::KEY_P,
	KeyCode::KEY_Q,
	KeyCode::KEY_R,
	KeyCode::KEY_S,
	KeyCode::KEY_T,
	KeyCode::KEY_U,
	KeyCode::KEY_V,
	KeyCode::KEY_W,
	KeyCode::KEY_X,
	KeyCode::KEY_Y,
	KeyCode::KEY_Z,
	KeyCode::KEY_LEFT_SUPER,
	KeyCode::KEY_RIGHT_SUPER,
	KeyCode::KEY_NONE,
	KeyCode::KEY_NONE,
	KeyCode::KEY_NONE,
	KeyCode::KEY_NUM_0,
	KeyCode::KEY_NUM_1,
	KeyCode::KEY_NUM_2,
	KeyCode::KEY_NUM_3,
	KeyCode::KEY_NUM_4,
	KeyCode::KEY_NUM_5,
	KeyCode::KEY_NUM_6,
	KeyCode::KEY_NUM_7,
	KeyCode::KEY_NUM_8,
	KeyCode::KEY_NUM_9,
	KeyCode::KEY_NUM_MULTIPLY,
	KeyCode::KEY_NUM_PLUS,
	KeyCode::KEY_NONE,
	KeyCode::KEY_NUM_MINUS,
	KeyCode::KEY_NUM_DOT,
	KeyCode::KEY_NUM_SLASH,
	KeyCode::KEY_F1,
	KeyCode::KEY_F2,
	KeyCode::KEY_F3,
	KeyCode::KEY_F4,
	KeyCode::KEY_F5,
	KeyCode::KEY_F6,
	KeyCode::KEY_F7,
	KeyCode::KEY_F8,
	KeyCode::KEY_F9,
	KeyCode::KEY_F10,
	KeyCode::KEY_F11,
	KeyCode::KEY_F12,
	KeyCode::KEY_NONE,
	KeyCode::KEY_NONE,
	KeyCode::KEY_NONE,
	KeyCode::KEY_NONE,
	KeyCode::KEY_NONE,
	KeyCode::KEY_NONE,
	KeyCode::KEY_NONE,
	KeyCode::KEY_NONE,
	KeyCode::KEY_NONE,
	KeyCode::KEY_NONE,
	KeyCode::KEY_NONE,
	KeyCode::KEY_NONE,
	KeyCode::KEY_NONE,
	KeyCode::KEY_NONE,
	KeyCode::KEY_NONE,
	KeyCode::KEY_NONE,
	KeyCode::KEY_NONE,
	KeyCode::KEY_NONE,
	KeyCode::KEY_NONE,
	KeyCode::KEY_NONE,
	KeyCode::KEY_NUM_LOCK,
	KeyCode::KEY_SCROLL_LOCK,
	KeyCode::KEY_NONE,
	KeyCode::KEY_NONE,
	KeyCode::KEY_NONE,
	KeyCode::KEY_NONE,
	KeyCode::KEY_NONE,
	KeyCode::KEY_NONE,
	KeyCode::KEY_NONE,
	KeyCode::KEY_NONE,
	KeyCode::KEY_NONE,
	KeyCode::KEY_NONE,
	KeyCode::KEY_NONE,
	KeyCode::KEY_NONE,
	KeyCode::KEY_NONE,
	KeyCode::KEY_NONE,
	KeyCode::KEY_LEFT_SHIFT,
	KeyCode::KEY_RIGHT_SHIFT,
	KeyCode::KEY_LEFT_CONTROL,
	KeyCode::KEY_RIGHT_CONTROL,
	KeyCode::KEY_LEFT_ALT,
	KeyCode::KEY_RIGHT_ALT,
	KeyCode::KEY_NONE,
	KeyCode::KEY_NONE,
	KeyCode::KEY_NONE,
	KeyCode::KEY_NONE,
	KeyCode::KEY_NONE,
	KeyCode::KEY_NONE,
	KeyCode::KEY_NONE,
	KeyCode::KEY_NONE,
	KeyCode::KEY_NONE,
	KeyCode::KEY_NONE,
	KeyCode::KEY_NONE,
	KeyCode::KEY_NONE,
	KeyCode::KEY_NONE,
	KeyCode::KEY_NONE,
	KeyCode::KEY_NONE,
	KeyCode::KEY_NONE,
	KeyCode::KEY_NONE,
	KeyCode::KEY_NONE,
	KeyCode::KEY_NONE,
	KeyCode::KEY_NONE,
	KeyCode::KEY_NONE,
	KeyCode::KEY_NONE,
	KeyCode::KEY_NONE,
	KeyCode::KEY_NONE,
	KeyCode::KEY_NONE,
	KeyCode::KEY_NONE,
	KeyCode::KEY_TILDE
};

#if defined(__clang__)
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wpedantic"
#elif defined(__GNUC__)
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wpedantic"
#endif
extern int main(int argc, char** args);
int WINAPI WinMain(HINSTANCE inst, HINSTANCE prev_inst, LPSTR cmd_line, int show_cmd) {
	g_instance = inst;
	return main(1, &cmd_line);
}
#if defined(__clang__)
#pragma clang diagnostic pop
#elif defined(__GNUC__)
#pragma GCC diagnostic pop
#endif

static WPARAM map_virtual_key_code(WPARAM virtual_key, LPARAM param) {
	WPARAM result = virtual_key;
	UINT scancode = (param>>16)&0x000000FF;
	bool is_extended = (param&0x01000000);
	switch(virtual_key) {
	case VK_SHIFT:
		result = MapVirtualKey(scancode, MAPVK_VSC_TO_VK_EX);
		break;
	case VK_CONTROL:
		result = is_extended?VK_RCONTROL:VK_LCONTROL;
		break;
	case VK_MENU:
		result = is_extended?VK_RMENU:VK_LMENU;
		break;
	}
	return result;
}
static LRESULT CALLBACK window_proc(HWND window_handle, UINT message, WPARAM param1, LPARAM param2) {
	return g_current_window.load()->window_proc(window_handle, message, param1, param2);
}

Win32Window::Win32Window(const std::string& title, unsigned width, unsigned height) :
	Window(),
	m_window_handle(),
	m_ctx(),
	m_window_thread(),
	m_window_created(false),
	m_switch_mouse_grab(false)
{
	m_type = WindowType::WINDOW_TYPE_WIN32;
	g_current_window = this;
	m_window_thread.reset(new std::thread(&Win32Window::window_thread_func, this, title, width, height));
	// Wait until window thread creates window
	LOG_VERBOSE("Waiting until window thread creates window");
	while(!m_window_created);
}

Win32Window::~Win32Window() {
	if(m_window_thread->joinable())
		m_window_thread->join();
	ReleaseDC(m_window_handle, m_ctx);
}

LRESULT Win32Window::window_proc(HWND window_handle, UINT message, WPARAM param1, LPARAM param2) {
	LRESULT result = 0;
	Event event;
	bool handled = false;
	switch(message) {
	case WM_KEYDOWN:
	case WM_SYSKEYDOWN:
		// FIXME: Implement proper handling of Alt+F4 combination. If there is no better way
		// then this should be fine I guess
		if(((param2>>29)&1) && param1==VK_F4) {
			event.m_type = EventType::EVENT_TYPE_WINDOW_CLOSE;
			DestroyWindow(window_handle);
			handled = true;
			break;
		}
		event.m_type = EventType::EVENT_TYPE_KEY_DOWN;
		param1 = map_virtual_key_code(param1, param2);
		if(param1>g_virtual_keycode_to_keycode.size())
			event.m_data.m_key_event.m_key = KeyCode::KEY_NONE;
		else
			event.m_data.m_key_event.m_key = g_virtual_keycode_to_keycode[param1];
		m_pressed_keyboard_keys[event.m_data.m_key_event.m_key] = true;
		handled = true;
		break;
	case WM_KEYUP:
	case WM_SYSKEYUP:
		event.m_type = EventType::EVENT_TYPE_KEY_UP;
		param1 = map_virtual_key_code(param1, param2);
		if(param1>g_virtual_keycode_to_keycode.size())
			event.m_data.m_key_event.m_key = KeyCode::KEY_NONE;
		else
			event.m_data.m_key_event.m_key = g_virtual_keycode_to_keycode[param1];
		m_pressed_keyboard_keys[event.m_data.m_key_event.m_key] = false;
		handled = true;
		break;
	case WM_CHAR:
		event.m_type = EventType::EVENT_TYPE_TEXT_ENTER;
		event.m_data.m_key_event.m_character_byte_count = WideCharToMultiByte(CP_UTF8, 0, (LPCWCH)&param1, -1, event.m_data.m_key_event.m_character_bytes, 4, nullptr, nullptr);
		handled = true;
		break;
	case WM_LBUTTONDOWN:
		event.m_type = EventType::EVENT_TYPE_MOUSE_BUTTON_DOWN;
		event.m_data.m_mouse_event.m_button = MouseButton::MOUSE_BUTTON_LEFT;
		m_pressed_mouse_buttons[event.m_data.m_mouse_event.m_button] = true;
		handled = true;
		break;
	case WM_LBUTTONUP:
		event.m_type = EventType::EVENT_TYPE_MOUSE_BUTTON_UP;
		event.m_data.m_mouse_event.m_button = MouseButton::MOUSE_BUTTON_LEFT;
		m_pressed_mouse_buttons[event.m_data.m_mouse_event.m_button] = false;
		handled = true;
		break;
	case WM_MBUTTONDOWN:
		event.m_type = EventType::EVENT_TYPE_MOUSE_BUTTON_DOWN;
		event.m_data.m_mouse_event.m_button = MouseButton::MOUSE_BUTTON_MIDDLE;
		m_pressed_mouse_buttons[event.m_data.m_mouse_event.m_button] = true;
		handled = true;
		break;
	case WM_MBUTTONUP:
		event.m_type = EventType::EVENT_TYPE_MOUSE_BUTTON_UP;
		event.m_data.m_mouse_event.m_button = MouseButton::MOUSE_BUTTON_MIDDLE;
		m_pressed_mouse_buttons[event.m_data.m_mouse_event.m_button] = false;
		handled = true;
		break;
	case WM_RBUTTONDOWN:
		event.m_type = EventType::EVENT_TYPE_MOUSE_BUTTON_DOWN;
		event.m_data.m_mouse_event.m_button = MouseButton::MOUSE_BUTTON_RIGHT;
		m_pressed_mouse_buttons[event.m_data.m_mouse_event.m_button] = true;
		handled = true;
		break;
	case WM_RBUTTONUP:
		event.m_type = EventType::EVENT_TYPE_MOUSE_BUTTON_UP;
		event.m_data.m_mouse_event.m_button = MouseButton::MOUSE_BUTTON_RIGHT;
		m_pressed_mouse_buttons[event.m_data.m_mouse_event.m_button] = false;
		handled = true;
		break;
	case WM_MOUSEMOVE:
		event.m_type = EventType::EVENT_TYPE_MOUSE_MOVE;
		m_mouse_x = event.m_data.m_mouse_event.m_x = LOWORD(param2);
		m_mouse_y = event.m_data.m_mouse_event.m_y = HIWORD(param2);
		if(m_mouse_grabbed) {
			RECT window_rect;
			GetWindowRect(window_handle, &window_rect);
			int width = window_rect.right-window_rect.left;
			int height = window_rect.bottom-window_rect.top;
			SetCursorPos(window_rect.left+width/2, window_rect.top+height/2);
		}
		handled = true;
		break;
	case WM_MOUSEWHEEL:
		event.m_type = EventType::EVENT_TYPE_MOUSE_WHEEL;
		event.m_data.m_mouse_event.m_wheel_offset = (GET_WHEEL_DELTA_WPARAM(param1)>0)-(GET_WHEEL_DELTA_WPARAM(param1)<0);
		handled = true;
		break;
	case WM_SIZE:
		event.m_type = EventType::EVENT_TYPE_WINDOW_RESIZE;
		event.m_data.m_window_event.m_width = LOWORD(param2);
		event.m_data.m_window_event.m_height = HIWORD(param2);
		handled = true;
		break;
	default:
		result = DefWindowProc(window_handle, message, param1, param2);
		break;
	}
	if(handled)
		push_event(event);
	return result;
}

HINSTANCE Win32Window::get_instance() const {
	return g_instance;
}

void Win32Window::finish_frame() {
	SwapBuffers(m_ctx);
}

void Win32Window::grab_mouse(bool grab) {
	m_mouse_grabbed = grab;
	m_switch_mouse_grab = true;
}

void Win32Window::window_thread_func(const std::string& title, unsigned width, unsigned height) {
	WNDCLASSW window_class={0};
	window_class.lpfnWndProc = ::window_proc;
	window_class.hInstance = g_instance;
	window_class.hCursor = LoadCursor(0, IDC_ARROW);
	const wchar_t class_name[] = L"polygun";
	window_class.lpszClassName = class_name;
	if(!RegisterClass(&window_class))
		LOG_FATAL("Failed to register window class (error code: %d)", GetLastError());

	// FIXME: Replace deprecated std::codecvt_utf8_utf16
#if defined(__clang__)
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
#endif
	std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> converter;
	std::wstring title_w = converter.from_bytes(title);
#if defined(__clang__)
#pragma clang diagnostic pop
#endif
	m_window_handle = CreateWindowEx(0, class_name, title_w.c_str(), WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, nullptr, nullptr, g_instance, nullptr);
	if(!m_window_handle)
		LOG_FATAL("Failed to create window (error code: %d)", GetLastError());

	m_ctx = GetDC(m_window_handle);

	ShowWindow(m_window_handle, true);
	m_window_created = true;

	MSG msg={0};
	while(GetMessage(&msg, m_window_handle, 0, 0)>0) {
		g_current_window = this;
		TranslateMessage(&msg);
		DispatchMessage(&msg);
		if(m_switch_mouse_grab) {
			if(m_mouse_grabbed)
				SetCapture(m_window_handle);
			else
				ReleaseCapture();
			ShowCursor(!m_mouse_grabbed);
			m_switch_mouse_grab = false;
		}
	}

	acquire();
	Event close_event;
	close_event.m_type = EventType::EVENT_TYPE_WINDOW_CLOSE;
	m_event_queue.push_back(close_event);
	release();
}
