#include "TeleportAura.h"

#include "Client.h"

#include "Mod/Teams.h"
#include "Mod/Scaffold.h"

#include "Utils/ChatUtils.h"
#include "Utils/PlayerUtils.h"
#include "Utils/MathUtils.h"
#include "Utils/MoveUtils.h"
#include "Utils/TimeUtils.h"

auto TeleportAura::onPacketSendBefore(Packet* packet) -> void {
	if (list.empty()) return;

	auto clientinstance = Client::clientinstance;
	if (!clientinstance) return;

	auto localplayer = clientinstance->getLocalPlayer();
	if (!localplayer) return;

	auto gamemode = localplayer->getGameMode();
	if (!gamemode) return;

	long long now = Utils::Time::getMs();

	if (packet->getID() == PacketID::PlayerAuthInput) {
		static long long start = now;

		static float nowaps = Utils::Math::getrandom(minaps, maxaps);
		if (now - start >= 1000.f / nowaps) {
			glm::vec3 pos = Utils::Move::getPosition(list[0]);
			glm::vec3 playerpos = Utils::Move::getPosition(localplayer);

			auto playerauthinput = reinterpret_cast<PlayerAuthInputPacket*>(packet);

			playerauthinput->setPos(glm::vec3(pos.x + 1.f, pos.y + 1.f, pos.z + 1.f));
			gamemode->attack(*list[0]);

			start = now;
		}
	}
}

auto TeleportAura::onClient() -> void {
	if (!enabled) return;

	auto clientinstance = Client::clientinstance;
	if (!clientinstance) return;

	auto localplayer = clientinstance->getLocalPlayer();
	if (!localplayer) return;

	auto level = localplayer->getLevel();
	if (!level) return;

	auto teamsMod = Client::findMod<Teams>(_("Teams"));
	auto scaffoldMod = Client::findMod<Scaffold>(_("Scaffold"));
	if (scaffoldMod->enabled && scaffoldMod->placing) {
		Utils::Chat::display_(_("Spoofed"), Utils::Chat::Type::GREEN, Utils::Chat::PrefixType::VALKYRIE);
		return;
	}

	std::string coloredNametag = localplayer->getNameTag();

	std::vector<Player*> list_;
	level->forEachPlayer([&](Player& player) {

		if (&player != localplayer && Utils::Players::isRealPlayer(&player)) {
			if (Utils::Math::getDistance(Utils::Move::getPosition(&player), Utils::Move::getPosition(localplayer)) < range) {
				std::string name = (&player)->getNameTag();

				if (!teamsMod->enabled || teamsMod->enabled && std::string(1, name.at(2)) != std::string(1, coloredNametag.at(2))) {
					name = Utils::String::removeSymbols(name);
					name = Utils::String::removeToEscape(name);

					bool isfriend = false;
					for (std::string cf : Client::friendlist) {
						if (cf == name)
							isfriend = true;
					}
					if (!isfriend)
						list_.push_back(&player);
				}
			}
		}

		return true;
		});

	list = list_;
}

auto TeleportAura::onClient4() -> void {
	name = Datas::Language::get().module.combat.teleportaura.name;
	description = Datas::Language::get().module.combat.teleportaura.description;
}
