#include "AutoTool.h"
#include "Client.h"

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

auto AutoTool::onStartDestroyBlock() -> void {
	auto clientinstance = Client::clientinstance;
	if (!clientinstance) return;

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

	auto playerinventory = localplayer->getPlayerInventory();
	if (!playerinventory) return;

	auto scaffoldMod = Client::findMod<Scaffold>(_("Scaffold"));
	if (scaffoldMod->enabled) return;

	oldslot = playerinventory->getSelectedSlot();
	destroying = true;
}

auto AutoTool::onStopDestroyBlock() -> void {
	auto clientinstance = Client::clientinstance;
	if (!clientinstance) return;

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

	auto playerinventory = localplayer->getPlayerInventory();
	if (!playerinventory) return;

	auto scaffoldMod = Client::findMod<Scaffold>(_("Scaffold"));
	if (scaffoldMod->enabled) return;

	playerinventory->setSelectedSlot(oldslot);

	destroying = false;
}

auto AutoTool::onImGuiRender() -> void {
	if (ImGui::IsMouseDown(0)) {
		stopdestroying = false;
	}
	else {
		stopdestroying = true;
	}
}

auto AutoTool::onWorldTick(Player* _this) -> void {
	auto clientinstance = Client::clientinstance;
	if (!clientinstance) return;

	auto blocksource = clientinstance->getBlockSource();
	if (!blocksource) return;

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

    auto playerinventory = _this->getPlayerInventory();
    if (!playerinventory) return;

	auto inventory = playerinventory->getInventory();
    if (!inventory) return;

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

	auto hitresult = level->getHitResult();

	auto regenMod = Client::findMod<Regen>(_("Regen"));
	if (regenMod->enabled && regenMod->destroying) {
		destroying = false;
		return;
	}

	if (!destroying) return;
	if (stopdestroying) return;

	glm::ivec3 blockpos = hitresult.mBlock;
	auto block = blocksource->getBlock(&blockpos);

	float maxspeed = 0.f;
	int slot = -1;
	for (int i = 0; i < 9; i++) {
		auto itemstack = inventory->getItemStack(i);
		if (!itemstack->getItem()) continue;

		int current = playerinventory->getSelectedSlot();
		playerinventory->setSelectedSlot(i);
		float speed = gamemode->getDestroyRate(*block);
		playerinventory->setSelectedSlot(current);
		if (maxspeed < speed) {
			maxspeed = speed;
			slot = i;
		}
	}

	if (slot == -1) return;

	if (spoof == 1) playerinventory->setHandSlot(oldslot);

	playerinventory->setSelectedSlot(slot);
}
