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

#include <LibGUI/Application.h>
#include <LibGUI/Window.h>
#if defined(RENDERER_LEGACY_GL)
#include <LibGUI/Painter.h>
#endif
#include <cstdio>
#include <cstdlib>
#include <map>

#include "common/logger.hpp"

using namespace polygun::window;

static const polygun::window::KeyCode g_serenityos_keycode_to_keycode[] = {
	polygun::window::KeyCode::KEY_NONE,
	polygun::window::KeyCode::KEY_ESCAPE,
	polygun::window::KeyCode::KEY_TAB,
	polygun::window::KeyCode::KEY_BACKSPACE,
	polygun::window::KeyCode::KEY_RETURN,
	polygun::window::KeyCode::KEY_INSERT,
	polygun::window::KeyCode::KEY_DELETE,
	polygun::window::KeyCode::KEY_PRINT_SCREEN,
	polygun::window::KeyCode::KEY_NONE,
	polygun::window::KeyCode::KEY_HOME,
	polygun::window::KeyCode::KEY_END,
	polygun::window::KeyCode::KEY_LEFT,
	polygun::window::KeyCode::KEY_UP,
	polygun::window::KeyCode::KEY_RIGHT,
	polygun::window::KeyCode::KEY_DOWN,
	polygun::window::KeyCode::KEY_PAGE_UP,
	polygun::window::KeyCode::KEY_PAGE_DOWN,
	polygun::window::KeyCode::KEY_LEFT_SHIFT,
	polygun::window::KeyCode::KEY_RIGHT_SHIFT,
	polygun::window::KeyCode::KEY_LEFT_CONTROL,
	polygun::window::KeyCode::KEY_LEFT_ALT,
	polygun::window::KeyCode::KEY_CAPS_LOCK,
	polygun::window::KeyCode::KEY_NUM_LOCK,
	polygun::window::KeyCode::KEY_SCROLL_LOCK,
	polygun::window::KeyCode::KEY_F1,
	polygun::window::KeyCode::KEY_F2,
	polygun::window::KeyCode::KEY_F3,
	polygun::window::KeyCode::KEY_F4,
	polygun::window::KeyCode::KEY_F5,
	polygun::window::KeyCode::KEY_F6,
	polygun::window::KeyCode::KEY_F7,
	polygun::window::KeyCode::KEY_F8,
	polygun::window::KeyCode::KEY_F9,
	polygun::window::KeyCode::KEY_F10,
	polygun::window::KeyCode::KEY_F11,
	polygun::window::KeyCode::KEY_F12,
	polygun::window::KeyCode::KEY_SPACE,
	polygun::window::KeyCode::KEY_NONE,
	polygun::window::KeyCode::KEY_NONE,
	polygun::window::KeyCode::KEY_NONE,
	polygun::window::KeyCode::KEY_NONE,
	polygun::window::KeyCode::KEY_NONE,
	polygun::window::KeyCode::KEY_NONE,
	polygun::window::KeyCode::KEY_QUOTE,
	polygun::window::KeyCode::KEY_NONE,
	polygun::window::KeyCode::KEY_NONE,
	polygun::window::KeyCode::KEY_NONE,
	polygun::window::KeyCode::KEY_NONE,
	polygun::window::KeyCode::KEY_COMMA,
	polygun::window::KeyCode::KEY_MINUS,
	polygun::window::KeyCode::KEY_DOT,
	polygun::window::KeyCode::KEY_SLASH,
	polygun::window::KeyCode::KEY_0,
	polygun::window::KeyCode::KEY_1,
	polygun::window::KeyCode::KEY_2,
	polygun::window::KeyCode::KEY_3,
	polygun::window::KeyCode::KEY_4,
	polygun::window::KeyCode::KEY_5,
	polygun::window::KeyCode::KEY_6,
	polygun::window::KeyCode::KEY_7,
	polygun::window::KeyCode::KEY_8,
	polygun::window::KeyCode::KEY_9,
	polygun::window::KeyCode::KEY_NONE,
	polygun::window::KeyCode::KEY_SEMICOLON,
	polygun::window::KeyCode::KEY_NONE,
	polygun::window::KeyCode::KEY_EQUALS,
	polygun::window::KeyCode::KEY_NONE,
	polygun::window::KeyCode::KEY_NONE,
	polygun::window::KeyCode::KEY_NONE,
	polygun::window::KeyCode::KEY_A,
	polygun::window::KeyCode::KEY_B,
	polygun::window::KeyCode::KEY_C,
	polygun::window::KeyCode::KEY_D,
	polygun::window::KeyCode::KEY_E,
	polygun::window::KeyCode::KEY_F,
	polygun::window::KeyCode::KEY_G,
	polygun::window::KeyCode::KEY_H,
	polygun::window::KeyCode::KEY_I,
	polygun::window::KeyCode::KEY_J,
	polygun::window::KeyCode::KEY_K,
	polygun::window::KeyCode::KEY_L,
	polygun::window::KeyCode::KEY_M,
	polygun::window::KeyCode::KEY_N,
	polygun::window::KeyCode::KEY_O,
	polygun::window::KeyCode::KEY_P,
	polygun::window::KeyCode::KEY_Q,
	polygun::window::KeyCode::KEY_R,
	polygun::window::KeyCode::KEY_S,
	polygun::window::KeyCode::KEY_T,
	polygun::window::KeyCode::KEY_U,
	polygun::window::KeyCode::KEY_V,
	polygun::window::KeyCode::KEY_W,
	polygun::window::KeyCode::KEY_X,
	polygun::window::KeyCode::KEY_Y,
	polygun::window::KeyCode::KEY_Z,
	polygun::window::KeyCode::KEY_LEFT_SQUARE_BRACKET,
	polygun::window::KeyCode::KEY_RIGHT_SQUARE_BRACKET,
	polygun::window::KeyCode::KEY_BACKSLASH,
	polygun::window::KeyCode::KEY_NONE,
	polygun::window::KeyCode::KEY_NONE,
	polygun::window::KeyCode::KEY_NONE,
	polygun::window::KeyCode::KEY_NONE,
	polygun::window::KeyCode::KEY_NONE,
	polygun::window::KeyCode::KEY_NONE,
	polygun::window::KeyCode::KEY_TILDE,
	polygun::window::KeyCode::KEY_LEFT_SUPER,
	polygun::window::KeyCode::KEY_CONTEXT
};

static const std::map<::KeyCode, polygun::window::KeyCode> g_serenityos_keycode_to_numpad_keycode = {
	{::KeyCode::Key_0, polygun::window::KeyCode::KEY_NUM_0},
	{::KeyCode::Key_1, polygun::window::KeyCode::KEY_NUM_1},
	{::KeyCode::Key_2, polygun::window::KeyCode::KEY_NUM_2},
	{::KeyCode::Key_3, polygun::window::KeyCode::KEY_NUM_3},
	{::KeyCode::Key_4, polygun::window::KeyCode::KEY_NUM_4},
	{::KeyCode::Key_5, polygun::window::KeyCode::KEY_NUM_5},
	{::KeyCode::Key_6, polygun::window::KeyCode::KEY_NUM_6},
	{::KeyCode::Key_7, polygun::window::KeyCode::KEY_NUM_7},
	{::KeyCode::Key_8, polygun::window::KeyCode::KEY_NUM_8},
	{::KeyCode::Key_9, polygun::window::KeyCode::KEY_NUM_9},
	{::KeyCode::Key_Slash, polygun::window::KeyCode::KEY_NUM_SLASH},
	{::KeyCode::Key_Minus, polygun::window::KeyCode::KEY_NUM_MINUS},
	{::KeyCode::Key_Plus, polygun::window::KeyCode::KEY_NUM_PLUS},
	{::KeyCode::Key_Period, polygun::window::KeyCode::KEY_NUM_DOT},
	{::KeyCode::Key_Left, polygun::window::KeyCode::KEY_LEFT},
	{::KeyCode::Key_Up, polygun::window::KeyCode::KEY_UP},
	{::KeyCode::Key_Right, polygun::window::KeyCode::KEY_RIGHT},
	{::KeyCode::Key_Down, polygun::window::KeyCode::KEY_DOWN}
};

static const std::map<GUI::MouseButton, polygun::window::MouseButton> g_serenityos_mousebutton_to_mousebutton = {
	{GUI::MouseButton::None, polygun::window::MouseButton::MOUSE_BUTTON_NONE},
	{GUI::MouseButton::Primary, polygun::window::MouseButton::MOUSE_BUTTON_LEFT},
	{GUI::MouseButton::Secondary, polygun::window::MouseButton::MOUSE_BUTTON_RIGHT},
	{GUI::MouseButton::Middle, polygun::window::MouseButton::MOUSE_BUTTON_MIDDLE},
	{GUI::MouseButton::Backward, polygun::window::MouseButton::MOUSE_BUTTON_AUX_1},
	{GUI::MouseButton::Forward, polygun::window::MouseButton::MOUSE_BUTTON_AUX_2}
};

struct WindowParams {
	std::string m_title;
	unsigned m_width;
	unsigned m_height;
	SerenityOSWindow* m_window;
};

static AK::Atomic<WindowParams*> g_window_params = nullptr;
static AK::Atomic<bool> g_window_created = false;

static intptr_t window_thread_func() {
	Main::Arguments args;
	AK::NonnullRefPtr<GUI::Application> gui_application = MUST(GUI::Application::create(args));

	WindowParams window_params = *g_window_params.load();
	AK::NonnullRefPtr<GUI::Window> window = MUST(GUI::Window::try_create());
	window->set_title(window_params.m_title.c_str());
	window->resize(window_params.m_width, window_params.m_height);
	SerenityOSWindowFrame* window_frame = new SerenityOSWindowFrame(window_params.m_window);
	window->set_main_widget(window_frame);
	window->show();
	g_window_created = true;

	intptr_t result = gui_application->exec();

	Event event;
	event.m_type = EventType::EVENT_TYPE_WINDOW_CLOSE;
	window_params.m_window->push_event(event);

	return result;
}

SerenityOSWindowFrame::SerenityOSWindowFrame(SerenityOSWindow* window) :
	GUI::Frame(),
	m_window(window),
	m_first_resize_event(true)
{}

void SerenityOSWindowFrame::paint_event(GUI::PaintEvent& ev) {
	GUI::Frame::paint_event(ev);
	GUI::Painter painter(*this);
	painter.add_clip_rect(ev.rect());
	m_window->m_window_mutex.lock();
	painter.draw_scaled_bitmap(frame_inner_rect(), *m_window->m_framebuffer, m_window->m_framebuffer->rect());
	m_window->m_window_mutex.unlock();
}

void SerenityOSWindowFrame::resize_event(GUI::ResizeEvent& ev) {
	GUI::Frame::resize_event(ev);
	if(m_first_resize_event) {
		m_first_resize_event = false;
		return;
	}
	Event event;
	event.m_type = EventType::EVENT_TYPE_WINDOW_RESIZE;
	event.m_data.m_window_event.m_width = ev.size().width();
	event.m_data.m_window_event.m_height = ev.size().height();
	m_window->m_window_mutex.lock();
	m_window->push_event(event);
#if defined(RENDERER_LEGACY_GL)
	m_window->m_gl_context = m_window->create_gl_context(ev.size().width(), ev.size().height());
#endif
	m_window->m_window_mutex.unlock();
}

void SerenityOSWindowFrame::keydown_event(GUI::KeyEvent& ev) {
	GUI::Frame::keydown_event(ev);
	key_event(ev);
	const AK::DeprecatedString str = ev.text();
	if(!str.is_empty() && (str.length()>1 || isprint(str[0]))) {
		Event event;
		event.m_type = EventType::EVENT_TYPE_TEXT_ENTER;
		event.m_data.m_key_event.m_character_byte_count = str.length();
		for(unsigned i = 0; i<event.m_data.m_key_event.m_character_byte_count && i<4; i++)
			event.m_data.m_key_event.m_character_bytes[i] = str[i];
		m_window->m_window_mutex.lock();
		m_window->push_event(event);
		m_window->m_window_mutex.unlock();
	}
}

void SerenityOSWindowFrame::keyup_event(GUI::KeyEvent& ev) {
	GUI::Frame::keyup_event(ev);
	key_event(ev);
	m_window->m_window_mutex.lock();
	if(m_window->m_pressed_keyboard_keys[polygun::window::KeyCode::KEY_RIGHT_ALT] && ev.key()==::KeyCode::Key_Alt) {
		Event event;
		event.m_type = EventType::EVENT_TYPE_KEY_UP;
		event.m_data.m_key_event.m_key = polygun::window::KeyCode::KEY_RIGHT_ALT;
		m_window->push_event(event);
		m_window->m_pressed_keyboard_keys[event.m_data.m_key_event.m_key] = false;
	}
	m_window->m_window_mutex.unlock();
}

void SerenityOSWindowFrame::mousemove_event(GUI::MouseEvent& ev) {
	GUI::Frame::mousemove_event(ev);
	Event event;
	event.m_type = EventType::EVENT_TYPE_MOUSE_MOVE;
	m_window->m_window_mutex.lock();
	m_window->m_mouse_x = event.m_data.m_mouse_event.m_x = ev.x();
	m_window->m_mouse_y = event.m_data.m_mouse_event.m_y = ev.y();
	m_window->push_event(event);
	m_window->m_window_mutex.unlock();
}

void SerenityOSWindowFrame::mousedown_event(GUI::MouseEvent& ev) {
	GUI::Frame::mousedown_event(ev);
	mouse_button_event(ev);
}

void SerenityOSWindowFrame::mouseup_event(GUI::MouseEvent& ev) {
	GUI::Frame::mouseup_event(ev);
	mouse_button_event(ev);
}

void SerenityOSWindowFrame::mousewheel_event(GUI::MouseEvent& ev) {
	GUI::Frame::mousewheel_event(ev);
	Event event;
	event.m_type = EventType::EVENT_TYPE_MOUSE_WHEEL;
	event.m_data.m_mouse_event.m_wheel_offset = 1-std::signbit(ev.wheel_delta_y())*2;
	m_window->m_window_mutex.lock();
	m_window->push_event(event);
	m_window->m_window_mutex.unlock();
}

void SerenityOSWindowFrame::key_event(GUI::KeyEvent& ev) {
	const bool pressed = ev.type()==GUI::Event::Type::KeyDown;
	Event event;
	event.m_type = pressed?EventType::EVENT_TYPE_KEY_DOWN:EventType::EVENT_TYPE_KEY_UP;
	if(ev.altgr() && ev.key()==::KeyCode::Key_Alt)
		event.m_data.m_key_event.m_key = polygun::window::KeyCode::KEY_RIGHT_ALT;
	else if(ev.modifiers()&KeyModifier::Mod_Keypad && g_serenityos_keycode_to_numpad_keycode.count(ev.key()))
		event.m_data.m_key_event.m_key = g_serenityos_keycode_to_numpad_keycode.at(ev.key());
	else if(ev.key()<sizeof(g_serenityos_keycode_to_keycode)/sizeof(polygun::window::KeyCode))
		event.m_data.m_key_event.m_key = g_serenityos_keycode_to_keycode[ev.key()];
	else
		event.m_data.m_key_event.m_key = polygun::window::KeyCode::KEY_NONE;
	m_window->m_window_mutex.lock();
	m_window->push_event(event);
	m_window->m_pressed_keyboard_keys[event.m_data.m_key_event.m_key] = pressed;
	m_window->m_window_mutex.unlock();
}

void SerenityOSWindowFrame::mouse_button_event(GUI::MouseEvent& ev) {
	const bool pressed = ev.type()==GUI::Event::Type::MouseDown;
	Event event;
	event.m_type = pressed?EventType::EVENT_TYPE_MOUSE_BUTTON_DOWN:EventType::EVENT_TYPE_MOUSE_BUTTON_UP;
	if(g_serenityos_mousebutton_to_mousebutton.count(ev.button())) {
		event.m_data.m_mouse_event.m_button = g_serenityos_mousebutton_to_mousebutton.at(ev.button());
		m_window->m_window_mutex.lock();
		m_window->m_pressed_mouse_buttons[event.m_data.m_mouse_event.m_button] = pressed;
		m_window->m_window_mutex.unlock();
	}
	else
		event.m_data.m_mouse_event.m_button = polygun::window::MouseButton::MOUSE_BUTTON_NONE;
	m_window->m_window_mutex.lock();
	m_window->push_event(event);
	m_window->m_window_mutex.unlock();
}

SerenityOSWindow::SerenityOSWindow(const std::string& title, unsigned width, unsigned height) :
#if defined(RENDERER_LEGACY_GL)
	m_gl_context(nullptr),
#endif
	m_window_thread(MUST(Threading::Thread::try_create(window_thread_func))),
	m_window_mutex(),
	m_framebuffer()
{
	m_type = WindowType::WINDOW_TYPE_SERENITYOS;
#if defined(RENDERER_LEGACY_GL)
	m_gl_context = create_gl_context(width, height);
#endif
	WindowParams params {
		title,
		width,
		height,
		this
	};
	g_window_params = &params;
	m_window_thread->start();
	LOG_VERBOSE("Waiting until window thread creates window");
	while(!g_window_created);
	g_window_created = false;
}

SerenityOSWindow::~SerenityOSWindow() {
	(void)m_window_thread->join();
}

#if defined(RENDERER_LEGACY_GL)
polygun::renderer::SerenityOSGLContext* SerenityOSWindow::create_gl_context(unsigned width, unsigned height) {
	if(m_gl_context)
		delete m_gl_context;
	m_framebuffer = MUST(Gfx::Bitmap::create(Gfx::BitmapFormat::BGRx8888, Gfx::IntSize{width, height}));
	return new renderer::SerenityOSGLContext(m_framebuffer.ptr());
}
#endif

size_t SerenityOSWindow::poll_events(Event& event) {
	m_window_mutex.lock();
	size_t result = Window::poll_events(event);
	m_window_mutex.unlock();
	return result;
}

void SerenityOSWindow::grab_mouse(bool grab) {

}
