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

#if defined(RENDERER_GL)
#include <GL/glx.h>
#endif
#include <X11/cursorfont.h>
#include <map>

#include "common/logger.hpp"

using namespace polygun::window;

// This will only work for standard keyboard mappings
// However fixing is not urgent so it should be fine like this for now
static const std::map<KeySym, polygun::window::KeyCode> g_x11_latin_keysym_to_keycode = {
	{XK_space, polygun::window::KeyCode::KEY_SPACE},
	{XK_apostrophe, polygun::window::KeyCode::KEY_QUOTE},
	{XK_comma, polygun::window::KeyCode::KEY_COMMA},
	{XK_minus, polygun::window::KeyCode::KEY_MINUS},
	{XK_period, polygun::window::KeyCode::KEY_DOT},
	{XK_slash, polygun::window::KeyCode::KEY_SLASH},
	{XK_0, polygun::window::KeyCode::KEY_0},
	{XK_1, polygun::window::KeyCode::KEY_1},
	{XK_2, polygun::window::KeyCode::KEY_2},
	{XK_3, polygun::window::KeyCode::KEY_3},
	{XK_4, polygun::window::KeyCode::KEY_4},
	{XK_5, polygun::window::KeyCode::KEY_5},
	{XK_6, polygun::window::KeyCode::KEY_6},
	{XK_7, polygun::window::KeyCode::KEY_7},
	{XK_8, polygun::window::KeyCode::KEY_8},
	{XK_9, polygun::window::KeyCode::KEY_9},
	{XK_semicolon, polygun::window::KeyCode::KEY_SEMICOLON},
	{XK_equal, polygun::window::KeyCode::KEY_EQUALS},
	{XK_bracketleft, polygun::window::KeyCode::KEY_LEFT_SQUARE_BRACKET},
	{XK_backslash, polygun::window::KeyCode::KEY_BACKSLASH},
	{XK_bracketright, polygun::window::KeyCode::KEY_RIGHT_SQUARE_BRACKET},
	{XK_grave, polygun::window::KeyCode::KEY_TILDE},
	{XK_a, polygun::window::KeyCode::KEY_A},
	{XK_b, polygun::window::KeyCode::KEY_B},
	{XK_c, polygun::window::KeyCode::KEY_C},
	{XK_d, polygun::window::KeyCode::KEY_D},
	{XK_e, polygun::window::KeyCode::KEY_E},
	{XK_f, polygun::window::KeyCode::KEY_F},
	{XK_g, polygun::window::KeyCode::KEY_G},
	{XK_h, polygun::window::KeyCode::KEY_H},
	{XK_i, polygun::window::KeyCode::KEY_I},
	{XK_j, polygun::window::KeyCode::KEY_J},
	{XK_k, polygun::window::KeyCode::KEY_K},
	{XK_l, polygun::window::KeyCode::KEY_L},
	{XK_m, polygun::window::KeyCode::KEY_M},
	{XK_n, polygun::window::KeyCode::KEY_N},
	{XK_o, polygun::window::KeyCode::KEY_O},
	{XK_p, polygun::window::KeyCode::KEY_P},
	{XK_q, polygun::window::KeyCode::KEY_Q},
	{XK_r, polygun::window::KeyCode::KEY_R},
	{XK_s, polygun::window::KeyCode::KEY_S},
	{XK_t, polygun::window::KeyCode::KEY_T},
	{XK_u, polygun::window::KeyCode::KEY_U},
	{XK_v, polygun::window::KeyCode::KEY_V},
	{XK_w, polygun::window::KeyCode::KEY_W},
	{XK_x, polygun::window::KeyCode::KEY_X},
	{XK_y, polygun::window::KeyCode::KEY_Y},
	{XK_z, polygun::window::KeyCode::KEY_Z},
	{XK_BackSpace, polygun::window::KeyCode::KEY_BACKSPACE},
	{XK_Tab, polygun::window::KeyCode::KEY_TAB},
	{XK_Return, polygun::window::KeyCode::KEY_RETURN},
	{XK_Pause, polygun::window::KeyCode::KEY_PAUSE},
	{XK_Scroll_Lock, polygun::window::KeyCode::KEY_SCROLL_LOCK},
	{XK_Escape, polygun::window::KeyCode::KEY_ESCAPE},
	{XK_Home, polygun::window::KeyCode::KEY_HOME},
	{XK_Left, polygun::window::KeyCode::KEY_LEFT},
	{XK_Up, polygun::window::KeyCode::KEY_UP},
	{XK_Right, polygun::window::KeyCode::KEY_RIGHT},
	{XK_Down, polygun::window::KeyCode::KEY_DOWN},
	{XK_Page_Up, polygun::window::KeyCode::KEY_PAGE_UP},
	{XK_Page_Down, polygun::window::KeyCode::KEY_PAGE_DOWN},
	{XK_End, polygun::window::KeyCode::KEY_END},
	{XK_Insert, polygun::window::KeyCode::KEY_INSERT},
	{XK_Print, polygun::window::KeyCode::KEY_PRINT_SCREEN},
	{XK_Menu, polygun::window::KeyCode::KEY_CONTEXT},
	{XK_Num_Lock, polygun::window::KeyCode::KEY_NUM_LOCK},
	{XK_KP_Enter, polygun::window::KeyCode::KEY_NUM_RETURN},
	{XK_KP_Home, polygun::window::KeyCode::KEY_NUM_7},
	{XK_KP_Left, polygun::window::KeyCode::KEY_NUM_4},
	{XK_KP_Up, polygun::window::KeyCode::KEY_NUM_8},
	{XK_KP_Right, polygun::window::KeyCode::KEY_NUM_6},
	{XK_KP_Down, polygun::window::KeyCode::KEY_NUM_2},
	{XK_KP_Page_Up, polygun::window::KeyCode::KEY_NUM_9},
	{XK_KP_Page_Down, polygun::window::KeyCode::KEY_NUM_3},
	{XK_KP_End, polygun::window::KeyCode::KEY_NUM_1},
	{XK_KP_Begin, polygun::window::KeyCode::KEY_NUM_5},
	{XK_KP_Insert, polygun::window::KeyCode::KEY_NUM_0},
	{XK_KP_Delete, polygun::window::KeyCode::KEY_NUM_DOT},
	{XK_KP_Multiply, polygun::window::KeyCode::KEY_NUM_MULTIPLY},
	{XK_KP_Add, polygun::window::KeyCode::KEY_NUM_PLUS},
	{XK_KP_Subtract, polygun::window::KeyCode::KEY_NUM_MINUS},
	{XK_KP_Divide, polygun::window::KeyCode::KEY_NUM_SLASH},
	{XK_F1, polygun::window::KeyCode::KEY_F1},
	{XK_F2, polygun::window::KeyCode::KEY_F2},
	{XK_F3, polygun::window::KeyCode::KEY_F3},
	{XK_F4, polygun::window::KeyCode::KEY_F4},
	{XK_F5, polygun::window::KeyCode::KEY_F5},
	{XK_F6, polygun::window::KeyCode::KEY_F6},
	{XK_F7, polygun::window::KeyCode::KEY_F7},
	{XK_F8, polygun::window::KeyCode::KEY_F8},
	{XK_F9, polygun::window::KeyCode::KEY_F9},
	{XK_F10, polygun::window::KeyCode::KEY_F10},
	{XK_F11, polygun::window::KeyCode::KEY_F11},
	{XK_F12, polygun::window::KeyCode::KEY_F12},
	{XK_Shift_L, polygun::window::KeyCode::KEY_LEFT_SHIFT},
	{XK_Shift_R, polygun::window::KeyCode::KEY_RIGHT_SHIFT},
	{XK_Control_L, polygun::window::KeyCode::KEY_LEFT_CONTROL},
	{XK_Control_R, polygun::window::KeyCode::KEY_RIGHT_CONTROL},
	{XK_Caps_Lock, polygun::window::KeyCode::KEY_CAPS_LOCK},
	{XK_Meta_L, polygun::window::KeyCode::KEY_LEFT_ALT},
	{XK_Meta_R, polygun::window::KeyCode::KEY_RIGHT_ALT},
	{XK_Alt_L, polygun::window::KeyCode::KEY_LEFT_ALT},
	{XK_Alt_R, polygun::window::KeyCode::KEY_RIGHT_ALT},
	{XK_Super_L, polygun::window::KeyCode::KEY_LEFT_SUPER},
	{XK_Super_R, polygun::window::KeyCode::KEY_RIGHT_SUPER},
	{XK_ISO_Level3_Shift, polygun::window::KeyCode::KEY_RIGHT_ALT},
	{XK_Delete, polygun::window::KeyCode::KEY_DELETE},
};

X11Window::X11Window(const std::string& title, unsigned width, unsigned height, renderer::RendererType renderer_type) :
#if defined(RENDERER_GL)
	m_glx_has_doublebuffer(true),
#endif
	m_display(XOpenDisplay(nullptr)),
	m_screen(DefaultScreen(m_display)),
	m_visual_info(nullptr),
	m_window_id(),
	m_wm_delete(XInternAtom(m_display, "WM_DELETE_WINDOW", false)),
	m_renderer_type(renderer_type),
	m_input_context(),
	m_prev_width(width),
	m_prev_height(height),
	m_was_mouse_grabbed(false),
	m_skip_motion_event(false),
	m_first_focus_out_event(true)
{
	m_type = WindowType::WINDOW_TYPE_X11;
	if(!m_display)
		throw std::runtime_error("Failed to open display");

	switch(renderer_type) {
	case renderer::RendererType::RENDERER_TYPE_GL:
	case renderer::RendererType::RENDERER_TYPE_LEGACY_GL:
#if defined(RENDERER_GL) || defined(RENDERER_LEGACY_GL)
		m_visual_info = setup_glx();
#else
		LOG_FATAL("Request to setup GLX while OpenGL renderer is not compiled in");
#endif
		break;
	}

	::Window root_window = RootWindow(m_display, m_visual_info->screen);
	Colormap colormap = XCreateColormap(m_display, root_window, m_visual_info->visual, AllocNone);
	XSetWindowAttributes window_attribs;
	window_attribs.colormap = colormap;
	window_attribs.border_pixel = 0;
	window_attribs.event_mask = KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask | PointerMotionMask | StructureNotifyMask | FocusChangeMask;
	m_window_id = XCreateWindow(m_display, root_window, 0, 0, width, height, 0, m_visual_info->depth, InputOutput, m_visual_info->visual, CWBorderPixel | CWColormap | CWEventMask, &window_attribs);
	XSetStandardProperties(m_display, m_window_id, title.c_str(), "polygun", None, nullptr, 0, nullptr);
	XSetWMProtocols(m_display, m_window_id, &m_wm_delete, 1);

	// setup input context
	XSetLocaleModifiers("");
	XIM im = XOpenIM(m_display, nullptr, nullptr, nullptr);
	if(!im) {
		XSetLocaleModifiers("@im=none");
		im = XOpenIM(m_display, nullptr, nullptr, nullptr);
	}
	m_input_context = XCreateIC(im, XNInputStyle, XIMPreeditNothing|XIMStatusNothing, XNClientWindow, m_window_id, XNFocusWindow, m_window_id, nullptr);
	XSetICFocus(m_input_context);

	XMapWindow(m_display, m_window_id);
}

X11Window::~X11Window() {
	XDestroyWindow(m_display, m_window_id);
	XFree(m_visual_info);
	if(m_display)
		XCloseDisplay(m_display);
}

size_t X11Window::poll_events(Event& event) {
	XEvent ev;
	while(XPending(m_display)) {
		XNextEvent(m_display, &ev);
		Event new_event;
		bool handled = false;
		switch(ev.type) {
		case KeyPress: {
			new_event.m_type = EventType::EVENT_TYPE_KEY_DOWN;
			KeySym sym = XLookupKeysym(&ev.xkey, 0);
			if(g_x11_latin_keysym_to_keycode.count(sym))
				new_event.m_data.m_key_event.m_key = g_x11_latin_keysym_to_keycode.at(sym);
			else
				new_event.m_data.m_key_event.m_key = polygun::window::KeyCode::KEY_NONE;
			m_pressed_keyboard_keys[new_event.m_data.m_key_event.m_key] = true;
			push_event(new_event);

			Status lookup_status;
			int length = Xutf8LookupString(m_input_context, &ev.xkey, new_event.m_data.m_key_event.m_character_bytes, 4, nullptr, &lookup_status);
			// workaround to not include some non-printable keys
			if(length==1 && !isprint(new_event.m_data.m_key_event.m_character_bytes[0]))
				break;
			if((lookup_status==XLookupChars || lookup_status==XLookupBoth) && length>0) {
				new_event.m_type = EventType::EVENT_TYPE_TEXT_ENTER;
				new_event.m_data.m_key_event.m_character_byte_count = static_cast<unsigned>(length);
				push_event(new_event);
			}
			break;
		}
		case KeyRelease: {
			new_event.m_type = EventType::EVENT_TYPE_KEY_UP;
			KeySym sym = XLookupKeysym(&ev.xkey, 0);
			if(g_x11_latin_keysym_to_keycode.count(sym))
				new_event.m_data.m_key_event.m_key = g_x11_latin_keysym_to_keycode.at(sym);
			else
				new_event.m_data.m_key_event.m_key = polygun::window::KeyCode::KEY_NONE;
			// Check if the key was actually released and then update keyboard table
			if(XEventsQueued(m_display, QueuedAlready)) {
				XEvent next_event;
				XPeekEvent(m_display, &next_event);
				if(next_event.type!=KeyPress || next_event.xkey.time!=ev.xkey.time || next_event.xkey.keycode!=ev.xkey.keycode)
					m_pressed_keyboard_keys[new_event.m_data.m_key_event.m_key] = false;
			}
			else
				m_pressed_keyboard_keys[new_event.m_data.m_key_event.m_key] = false;
			handled = true;
			break;
		}
		case ButtonPress:
		case ButtonRelease:
			if(ev.xbutton.button<=Button3) {
				new_event.m_type = ev.xbutton.type==ButtonPress?EventType::EVENT_TYPE_MOUSE_BUTTON_DOWN:EventType::EVENT_TYPE_MOUSE_BUTTON_UP;
				new_event.m_data.m_mouse_event.m_button = static_cast<MouseButton>(ev.xbutton.button);
				m_pressed_mouse_buttons[new_event.m_data.m_mouse_event.m_button] = ev.xbutton.type==ButtonPress;
				handled = true;
			}
			else if(ev.xbutton.button<=Button5) {
				if(ev.type==ButtonPress) {
					new_event.m_type = EventType::EVENT_TYPE_MOUSE_WHEEL;
					new_event.m_data.m_mouse_event.m_wheel_offset = 1-2*(ev.xbutton.button-Button4);
					handled = true;
				}
			}
			else {
				new_event.m_type = ev.xbutton.type==ButtonPress?EventType::EVENT_TYPE_MOUSE_BUTTON_DOWN:EventType::EVENT_TYPE_MOUSE_BUTTON_UP;
				new_event.m_data.m_mouse_event.m_button = static_cast<MouseButton>(ev.xbutton.button-6+MouseButton::MOUSE_BUTTON_AUX_1);
				m_pressed_mouse_buttons[new_event.m_data.m_mouse_event.m_button] = ev.xbutton.type==ButtonPress;
				handled = true;
			}
			break;
		case MotionNotify:
			if(m_skip_motion_event) {
				m_skip_motion_event = false;
				break;
			}
			new_event.m_type = EventType::EVENT_TYPE_MOUSE_MOVE;
			m_mouse_x = new_event.m_data.m_mouse_event.m_x = ev.xmotion.x;
			m_mouse_y = new_event.m_data.m_mouse_event.m_y = ev.xmotion.y;
			if(m_mouse_grabbed) {
				XWarpPointer(m_display, None, m_window_id, 0, 0, 0, 0, m_prev_width/2, m_prev_height/2);
				m_skip_motion_event = true;
				XFlush(m_display);
			}
			handled = true;
			break;
		case ConfigureNotify:
			if(m_prev_width!=static_cast<unsigned>(ev.xconfigure.width) || m_prev_height!=static_cast<unsigned>(ev.xconfigure.height)) {
				m_prev_width = static_cast<unsigned>(ev.xconfigure.width);
				m_prev_height = static_cast<unsigned>(ev.xconfigure.height);
				new_event.m_type = EventType::EVENT_TYPE_WINDOW_RESIZE;
				new_event.m_data.m_window_event.m_width = m_prev_width;
				new_event.m_data.m_window_event.m_height = m_prev_height;
				handled = true;
			}
			break;
		case FocusIn:
			if(m_was_mouse_grabbed)
				grab_mouse(true);
			m_first_focus_out_event = true;
			break;
		case FocusOut:
			if(!m_first_focus_out_event)
				break;
			m_was_mouse_grabbed = m_mouse_grabbed;
			if(m_mouse_grabbed)
				grab_mouse(false);
			m_first_focus_out_event = false;
			break;
		case ClientMessage:
			if(static_cast<Atom>(ev.xclient.data.l[0])==m_wm_delete) {
				new_event.m_type = EventType::EVENT_TYPE_WINDOW_CLOSE;
				handled = true;
			}
			break;
		}
		if(handled)
			push_event(new_event);
	}

	return Window::poll_events(event);
}

void X11Window::finish_frame() {
	switch(m_renderer_type) {
	case renderer::RendererType::RENDERER_TYPE_GL:
	case renderer::RendererType::RENDERER_TYPE_LEGACY_GL:
#if defined(RENDERER_GL) || defined(RENDERER_LEGACY_GL)
		if(m_glx_has_doublebuffer)
			glXSwapBuffers(m_display, m_window_id);
		break;
#endif
	}
}

void X11Window::grab_mouse(bool grab) {
	Cursor cursor;
	if(grab) {
		static const char empty_pixmap_data[] = {0, 0, 0, 0, 0, 0, 0, 0};
		Pixmap empty_pixmap = XCreateBitmapFromData(m_display, m_window_id, empty_pixmap_data, 8, 8);
		XColor black;
		black.red = black.green = black.blue = 0;
		cursor = XCreatePixmapCursor(m_display, empty_pixmap, empty_pixmap, &black, &black, 0, 0);
		XFreePixmap(m_display, empty_pixmap);
	}
	else
		cursor = XCreateFontCursor(m_display, XC_left_ptr);
	XDefineCursor(m_display, m_window_id, cursor);
	XFreeCursor(m_display, cursor);
	m_mouse_grabbed = grab;
}

#if defined(RENDERER_GL) || defined(RENDERER_LEGACY_GL)
XVisualInfo* X11Window::setup_glx() {
	// check if GLX is supported
	int dummy;
	if(!glXQueryExtension(m_display, &dummy, &dummy))
		LOG_FATAL("X display doesn't support GLX");

	XVisualInfo* visual_info;
	int doublebuffer[] = {
		GLX_RGBA,
		GLX_RED_SIZE, 1,
		GLX_GREEN_SIZE, 1,
		GLX_BLUE_SIZE, 1,
		GLX_DEPTH_SIZE, 12,
		GLX_DOUBLEBUFFER,
		None
	};
	int singlebuffer[] = {
		GLX_RGBA,
		GLX_RED_SIZE, 1,
		GLX_BLUE_SIZE, 1,
		GLX_GREEN_SIZE, 1,
		GLX_DEPTH_SIZE, 12,
		None
	};
	if(!(visual_info = glXChooseVisual(m_display, m_screen, doublebuffer))) {
		LOG_VERBOSE("Doublebuffer is not supported, trying singlebuffer");
		if(!(visual_info = glXChooseVisual(m_display, m_screen, singlebuffer)))
			LOG_FATAL("Failed to choose GLX visual");
		m_glx_has_doublebuffer = false;
	}

	return visual_info;
}
#endif
