#include "client/render/gui/SummonMenu.h"
#include "client/Client.h"
#include "client/render/gui/imgui/imgui.h"

namespace td {
namespace gui {

SummonMenu::SummonMenu(client::Client* client) : GuiWidget(client), m_MenuOpened(true) {
	m_Values.fill(0);
	SetCooldown(10);
}

void SummonMenu::SetCooldown(float cooldown) {
	m_LastCooldown = cooldown;
	m_Cooldown = cooldown;
}

void SummonMenu::Render() {
	if (m_Cooldown > 0)
		m_Cooldown = std::max(0.0f, m_Cooldown - ImGui::GetIO().DeltaTime);

	if (m_MenuOpened) {
		ImGui::Begin("Summon", &m_MenuOpened);
		ImTextureID my_tex_id = ImGui::GetIO().Fonts->TexID;
		for (int i = 0; i < m_MobTypeCount / 2; i++) {
			ImGui::SameLine();
			ImGui::PushID(i);
			ImGui::Image(my_tex_id, ImVec2(100, 100));
			ImGui::PopID();
		}
		ImGui::Separator();
		ImGui::PushItemWidth(m_ImageWidth);
		for (int i = 0; i < m_MobTypeCount / 2; i++) {
			ImGui::SameLine();
			ImGui::PushID(i);
			if (ImGui::InputInt("", m_Values.data() + i, 1, 10)) {
				SetSummonMax(i);
			}
			ImGui::PopID();
		}
		ImGui::PopItemWidth();
		ImGui::Separator();
		for (int i = m_MobTypeCount / 2; i < m_MobTypeCount; i++) {
			ImGui::SameLine();
			ImGui::PushID(i);
			ImGui::Image(my_tex_id, ImVec2(100, 100));
			ImGui::PopID();
		}
		ImGui::Separator();
		ImGui::PushItemWidth(m_ImageWidth);
		for (int i = m_MobTypeCount / 2; i < m_MobTypeCount; i++) {
			ImGui::SameLine();
			ImGui::PushID(i);
			if (ImGui::InputInt("", m_Values.data() + i, 1, m_MobTypeCount)) {
				SetSummonMax(i);
			}
			ImGui::PopID();
		}
		ImGui::PopItemWidth();
		if (m_Cooldown > 0) {
			ImGui::ProgressBar((m_LastCooldown - m_Cooldown) / m_LastCooldown, {}, std::string{ std::to_string((int)m_Cooldown + 1) + "s" }.c_str());
		} else if (ImGui::Button("Send")) {
			std::vector<protocol::MobSend> mobSent;
			protocol::MobSend mobSend;
			for (int i = 0; i < m_MobTypeCount; i++) {
				if (m_Values[i] != 0) {
					mobSend.mobCount = m_Values[i];
					mobSend.mobLevel = 1;   // TODO: add mob levels
					mobSend.mobType = td::game::MobType(i);
					mobSent.push_back(mobSend);
				}
			}
			if (mobSent.size() > 0) {
				m_Client->SendMobs(mobSent);
				m_Values.fill(0);
#ifdef NDEBUG
				SetCooldown(10);
#endif
			}
		}
		ImGui::End();
	}
}

void SummonMenu::SetSummonMax(int valueIndex) {
	int& value = m_Values[valueIndex];
	value = std::max(0, value);
	value = std::min(12, value);
	int total = 0;
	for (std::size_t i = 0; i < m_Values.size(); i++) {
		total += m_Values[i];
	}
	if (total == 13) // if the total is greater than the maximum, we substract the value
		value--;
}

} // namespace gui
} // namespace td
