/*
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.
*/

#ifndef POLYGUN_GUI_TEXT_EDIT_HPP
#define POLYGUN_GUI_TEXT_EDIT_HPP

#include "game/gui/component.hpp"
#include "game/gui/style_change_listener.hpp"

#include <chrono>
#include <vector>

#include "game/renderer/font.hpp"

namespace polygun::engine {
	class Engine;
}

namespace polygun::renderer {
	class Texture;
}

namespace polygun::gui {
	class TextEdit final : public Component, public StyleChangeListener {
	public:
		TextEdit(engine::Engine* engine, Constraint* x, Constraint* y, Constraint* width, Constraint* height, const std::string& id);
		TextEdit(engine::Engine* engine, xml::XMLNode* node);
		virtual ~TextEdit() override;

		const std::string& get_text_buffer() const { return m_text_buffer; }

		virtual void set_highlighted(bool highlighted) override;
		virtual void render(renderer::GUIRenderer* renderer) override;
		virtual bool update(const window::Event& event) override;
		virtual void on_style_change() override;

	private:
		engine::Engine* m_engine;
		renderer::Texture* m_text_texture;
		std::string m_text_buffer;
		unsigned m_text_offset;
		std::vector<std::unique_ptr<renderer::Font::RasterizedGlyph>> m_glyph_info;
		std::chrono::time_point<std::chrono::steady_clock> m_prev_cursor_change;
		bool m_render_cursor;
		unsigned m_cursor_x;
		size_t m_cursor_offset;

	private:
		void update_text_texture();
		void update_cursor_offset(size_t glyph_index);
		void update_cursor_x();
	};
}

#endif // POLYGUN_GUI_TEXT_EDIT_HPP
