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

#include "game/engine/engine.hpp"
#include "game/renderer/texture.hpp"
#include "game/gui/style.hpp"
#include "game/window/event.hpp"
#include "game/window/window.hpp"

using namespace polygun::gui;

static inline bool is_utf8_multibyte_continuation(unsigned char ch) {
	return ch>>6==2;
}

TextEdit::TextEdit(engine::Engine* engine, Constraint* x, Constraint* y, Constraint* width, Constraint* height, const std::string& id) :
	Component(x, y, width, height, id),
	StyleChangeListener(),
	m_engine(engine),
	m_text_texture(engine->get_master_renderer()->create_texture()),
	m_text_buffer(),
	m_text_offset(0),
	m_glyph_info(),
	m_prev_cursor_change(),
	m_render_cursor(false),
	m_cursor_x(0),
	m_cursor_offset(0)
{
	update_text_texture();
}

TextEdit::TextEdit(engine::Engine* engine, xml::XMLNode* node) :
	Component(node),
	StyleChangeListener(),
	m_engine(engine),
	m_text_texture(engine->get_master_renderer()->create_texture()),
	m_text_buffer(),
	m_text_offset(0),
	m_glyph_info(),
	m_prev_cursor_change(),
	m_render_cursor(false),
	m_cursor_x(0),
	m_cursor_offset(0)
{
	update_text_texture();
}

TextEdit::~TextEdit() {
	delete m_text_texture;
}

void TextEdit::render(renderer::GUIRenderer* renderer) {
	const float width = std::min(m_parent->get_right(), get_right())-get_x();
	const float height = std::min(m_parent->get_bottom(), get_bottom())-get_y();
	const unsigned extrusion = Style::get().m_extrusion_size;
	renderer->fill_rect(glm::vec2(get_x(), get_y()), glm::vec2(width, height), add_to_color(Style::get().m_background_color, glm::vec4ub(100, 100, 100, 0)));
	renderer->fill_rect(glm::vec2(get_x()+extrusion, get_y()+extrusion), glm::vec2(width, height), subtract_from_color(Style::get().m_background_color, glm::vec4ub(30, 30, 30, 0)));
	renderer->fill_rect(glm::vec2(get_x()+extrusion, get_y()+extrusion), glm::vec2(width-extrusion, height-extrusion), Style::get().m_lower_background_color);
	renderer->render_cropped_texture(glm::vec2(get_x()+3, get_y()+(height-m_text_texture->get_height())/2), m_text_texture, glm::vec2(1, 1),
		math::Rect(m_text_offset, 0, width-2, m_text_texture->get_height()));
	if(m_render_cursor)
		renderer->fill_rect(glm::vec2(get_x()+3+m_cursor_x, get_y()+1), glm::vec2(2, height-3), glm::vec4ub(0, 0, 0, 255));

	if(m_highlighted && std::chrono::steady_clock::now()-m_prev_cursor_change>=std::chrono::duration<double>(0.5)) {
		m_render_cursor = !m_render_cursor;
		m_prev_cursor_change = std::chrono::steady_clock::now();
	}
}

void TextEdit::set_highlighted(bool highlighted) {
	if((m_highlighted = highlighted)) {
		m_prev_cursor_change = std::chrono::steady_clock::now();
		m_render_cursor = true;
	}
	else
		m_render_cursor = false;
}

bool TextEdit::update(const window::Event& event) {
	const float width = std::min(m_parent->get_right(), get_right()+1)-get_x();
	const float height = std::min(m_parent->get_bottom(), get_bottom()+1)-get_y();
	switch(event.m_type) {
	case window::EventType::EVENT_TYPE_KEY_DOWN:
		if(m_highlighted) {
			switch(event.m_data.m_key_event.m_key) {
			case window::KeyCode::KEY_BACKSPACE:
				if(m_cursor_offset>0) {
					while(is_utf8_multibyte_continuation(m_text_buffer[m_cursor_offset-1]))
						m_text_buffer.erase(m_text_buffer.begin()+(--m_cursor_offset));
					m_text_buffer.erase(m_text_buffer.begin()+(--m_cursor_offset));
					update_text_texture();
					update_cursor_x();
				}
				break;
			case window::KeyCode::KEY_HOME:
				m_cursor_offset = 0;
				m_cursor_x = 0;
				m_text_offset = 0;
				break;
			case window::KeyCode::KEY_DELETE:
				if(m_cursor_offset<m_text_buffer.size()) {
					m_text_buffer.erase(m_text_buffer.begin()+m_cursor_offset);
					while(m_cursor_offset<m_text_buffer.size() && is_utf8_multibyte_continuation(m_text_buffer[m_cursor_offset]))
						m_text_buffer.erase(m_text_buffer.begin()+m_cursor_offset);
					update_text_texture();
					update_cursor_x();
				}
				break;
			case window::KeyCode::KEY_END:
				m_cursor_offset = m_text_buffer.size();
				update_cursor_x();
				m_text_offset = m_text_texture->get_width()-width;
				break;
			case window::KeyCode::KEY_LEFT:
				if(m_cursor_offset>0) {
					while(is_utf8_multibyte_continuation(m_text_buffer[m_cursor_offset-1]))
						m_cursor_offset--;
					m_cursor_offset--;
					update_cursor_x();
				}
				break;
			case window::KeyCode::KEY_RIGHT:
				if(m_cursor_offset<m_text_buffer.size()) {
					m_cursor_offset++;
					while(m_cursor_offset<m_text_buffer.size() && is_utf8_multibyte_continuation(m_text_buffer[m_cursor_offset]))
						m_cursor_offset++;
					update_cursor_x();
				}
			default:
				break;
			}
		}
		break;
	case window::EventType::EVENT_TYPE_TEXT_ENTER:
		if(m_highlighted) {
			for(unsigned i = 0; i<event.m_data.m_key_event.m_character_byte_count; i++) {
				m_text_buffer.insert(m_cursor_offset, 1, event.m_data.m_key_event.m_character_bytes[i]);
				m_cursor_offset++;
			}
			update_text_texture();
			update_cursor_x();
			return true;
		}
		break;
	case window::EventType::EVENT_TYPE_MOUSE_BUTTON_DOWN:
		if(m_engine->get_window()->is_mouse_inside_area(glm::vec2(get_x()-1, get_y()-1), glm::vec2(width, height)) &&
			event.m_data.m_mouse_event.m_button==window::MouseButton::MOUSE_BUTTON_LEFT) {
			if(!m_highlighted)
				m_engine->get_gui_master().request_highlight(this);
			const int mouse_x = m_engine->get_window()->get_mouse_x();
			if(m_engine->get_window()->is_mouse_inside_area(glm::vec2(get_x()+3, get_y()), glm::vec2(m_text_texture->get_width(), height))) {
				const int local_mouse_x = mouse_x-get_x()-3;
				for(size_t i = 0; i<m_glyph_info.size(); i++) {
					const std::unique_ptr<renderer::Font::RasterizedGlyph>& glyph = m_glyph_info[i];
					const int local_glyph_x = static_cast<int>(glyph->m_x-m_text_offset);
					if(local_mouse_x>=local_glyph_x && local_mouse_x<local_glyph_x+static_cast<int>(glyph->m_width)/2) {
						m_cursor_x = local_glyph_x;
						update_cursor_offset(i);
					}
					else if(local_mouse_x>=local_glyph_x+static_cast<int>(glyph->m_width)/2 && local_mouse_x<=local_glyph_x+static_cast<int>(glyph->m_width)) {
						m_cursor_x = local_glyph_x+glyph->m_width;
						update_cursor_offset(i+1);
					}
				}
			}
			else if(mouse_x<get_x()+3) {
				m_cursor_x = 0;
				m_cursor_offset = 0;
			}
			else {
				m_cursor_x = m_text_texture->get_width()-m_text_offset;
				m_cursor_offset = m_text_buffer.size();
			}
			return true;
		}
	default:
		break;
	}
	return false;
}

void TextEdit::on_style_change() {
	update_text_texture();
}

void TextEdit::update_text_texture() {
	m_glyph_info.clear();
	Style::get().m_font.render_glyphs(m_text_buffer.empty()?" ":m_text_buffer, 16, Style::get().m_text_color, m_glyph_info);
	std::unique_ptr<renderer::Surface> surf = Style::get().m_font.render_text(m_glyph_info);
	m_text_texture->load_from_surface(*surf);
}

void TextEdit::update_cursor_offset(size_t glyph_index) {
	// to understand following code please learn about Unicode Transformation Format 8 (UTF-8)
	size_t temp_index = 0;
	for(size_t i = 0; i<m_text_buffer.size(); i++) {
		if(is_utf8_multibyte_continuation(m_text_buffer[i]))
			continue;
		if(temp_index==glyph_index) {
			m_cursor_offset = i;
			break;
		}
		temp_index++;
	}
}

void TextEdit::update_cursor_x() {
	if(m_cursor_offset==0) {
		m_cursor_x = 0;
		return;
	}
	const float width = std::min(m_parent->get_right(), get_right()+1)-get_x();
	size_t glyph_index = 0;
	size_t i = 0;
	do {
		i++;
		if(is_utf8_multibyte_continuation(m_text_buffer[i]))
			continue;
		glyph_index++;
	}
	while(i<m_cursor_offset);
	const std::unique_ptr<renderer::Font::RasterizedGlyph>& glyph = m_glyph_info[glyph_index-1];
	m_cursor_x = glyph->m_x+glyph->m_width-m_text_offset;
	if(m_cursor_x>width-5) {
		m_text_offset+=glyph->m_width;
		m_cursor_x = width-5;
	}
	else if(glyph->m_x<m_text_offset) {
		m_text_offset-=glyph->m_width;
		m_cursor_x = 0;
	}
	if(m_text_offset>m_text_texture->get_width())
		m_text_offset = 0;
	if(m_text_offset>0 && m_text_offset+width>m_text_texture->get_width())
		m_text_offset = m_text_texture->get_width()-width-2;
}
