#include "client/render/gui/TowerUpgradePopup.h"

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

#include "td/game/Towers.h"

#include "client/Client.h"

namespace td {
namespace gui {

TowerUpgradePopup::TowerUpgradePopup(client::Client* client) : GuiWidget(client), m_ShouldBeClosed(false), m_Opened(false) {

}

void TowerUpgradePopup::SetClickPos(const Vec2f& worldPos) {
	m_ClickWorldPos = worldPos;
}

bool TowerUpgradePopup::IsPopupOpened() {
	return m_Opened;
}

void TowerUpgradePopup::Render() {
	if (ImGui::BeginPopup("TowerUpgrade")) {
		ImGui::BeginChild("TowerUpgradePopupChild", { 450, 350 });
		if (m_ShouldBeClosed) {
			ImGui::CloseCurrentPopup();
			ImGui::EndPopup();
			return;
		}

		game::TowerPtr tower = m_Client->GetGame().GetWorld().GetTower(m_ClickWorldPos);
		if (tower == nullptr) {
			ImGui::EndPopup();
			return;
		}
		ImGui::Text("Tower : %s", game::TowerFactory::GetTowerName(tower->GetType()).c_str());

		for (int y = 0; y < 3; y++) { // path: 0 -> top  1 -> middle  2 -> bottom
			for (int x = 0; x < 4; x++) { // level: 1, 2, 3, 4

				if (x > 0)
					ImGui::SameLine();

				std::uint8_t currentLevel = x + 1;
				game::TowerPath currentPath = game::TowerPath(y);

				const game::TowerStats* towerStats = game::GetTowerStats(tower->GetType(), { currentLevel, currentPath });
				game::TowerPath towerPath = tower->GetLevel().GetPath();

				bool disabled = towerStats == nullptr;

				int towerLevel = tower->GetLevel().GetLevel();

				bool alreadyUpgraded = currentLevel <= towerLevel;
				bool canUpgrade = (towerLevel + 1) == currentLevel;

				if (canUpgrade && towerPath != game::TowerPath::Base) {
					if (currentPath != towerPath) {
						canUpgrade = false;
					}
				}

				ImGui::PushID(x * 4 + y);
				if (disabled) {
					ImGui::BeginDisabled();
					ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0, 0, 0, 0));
					ImGui::Button("", ImVec2(100, 100));
					ImGui::PopStyleColor();
					ImGui::EndDisabled();
				} else if (alreadyUpgraded) {
					ImGui::BeginDisabled();
					ImGui::Button("Already", ImVec2(100, 100));
					ImGui::EndDisabled();
				} else if (canUpgrade) {
					if (ImGui::Button("Upgrade", ImVec2(100, 100))) {
						m_Client->UpgradeTower(tower->GetID(), { currentLevel, currentPath });
					}
				} else {
					ImGui::BeginDisabled();
					ImGui::Button("Locked", ImVec2(100, 100));
					ImGui::EndDisabled();
				}
				ImGui::PopID();
			}
		}

		ImGui::EndChild();
		ImGui::EndPopup();

		m_Opened = true;
		return;
	}

	m_Opened = false;
}

} // namespace gui
} // namespace td