#include "client/gui/GameChatGui.h"

#include "blitz/misc/Format.h"
#include "blitz/misc/Log.h"
#include "client/gui/ColorFulText.h"
#include "client/gui/GuiWidget.h"
#include <client/Client.h>
#include <imgui.h>
#include <string>

namespace blitz {
namespace gui {

GameChatGui::GameChatGui(GuiWidget* parent, Client* client) : GuiWidget(parent, client) {
	m_Client->BindListener(this);
	InputBuf[0] = '\0';
	Enable();
}

void GameChatGui::Draw(const char* title, bool* p_open) {
	static int chat_width = 620;
	static int chat_height = 450;
	static int chatInput_width = 590;
	static int scrolling_width = chat_height - 90;
	ImGui::SetNextWindowPos(ImVec2(0, ImGui::GetIO().DisplaySize.y - chat_height));
	ImGui::SetNextWindowSize(ImVec2(chat_width, chat_height));
	if (!ImGui::Begin(title, p_open, GetWindowFullScreenFlags())) {
		ImGui::End();
		return;
	}
	ImGui::PushStyleColor(ImGuiCol_Text, ImVec4(1.0f, 0.0f, 0.0f, 0.73f));
	ImGui::TextWrapped("Voici le chat de BLITZ");
	if (ImGui::BeginChild("ScrollingRegion", ImVec2(0, chat_height - 90), false, ImGuiWindowFlags_AlwaysVerticalScrollbar)) {
		for (const auto& line : m_Lines) {
			RenderColorfulText(line);
		}
	}
	ImGui::PopStyleColor();
	ImGui::EndChild();
	ImGuiInputTextFlags input_text_flags = ImGuiInputTextFlags_EnterReturnsTrue | ImGuiInputTextFlags_EscapeClearsAll;

	if (m_FocusRequested) {
		ImGui::SetKeyboardFocusHere(0);
		m_FocusRequested = false;
	}

	const static ImVec4 chatColorInputText = {1.0f, 0.0f, 0.0f, 0.27f};
	ImGui::SetNextItemWidth(chatInput_width);
	ImGui::PushStyleColor(ImGuiCol_FrameBg, chatColorInputText);
	if (ImGui::InputText(" ", InputBuf, IM_ARRAYSIZE(InputBuf), input_text_flags) && InputBuf[0] != '\0') {
		m_Client->SendChatText(InputBuf);
		InputBuf[0] = '\0';
	}
	ImGui::PopStyleColor();

	ImGui::End();
}

void GameChatGui::Render() {
	static bool showCHAT = false;

	if (!IsEnabled())
		return;

	if (ImGui::IsKeyPressed(ImGuiKey_Enter)) {
		showCHAT = true;
		m_FocusRequested = true;
	} else if (ImGui::IsKeyPressed(ImGuiKey_Escape)) {
		showCHAT = false;
	}

	if (showCHAT) {
		Draw("Chat BLITZ", nullptr);
	}
}

void GameChatGui::OnTextChatReceived(const protocol::ColoredText& text) {
	// rajouter des lignes dans le chat
	m_Lines.push_back(text);
}

}  // namespace gui
}  // namespace blitz
