#include "ChestStealer.h"
#include "Client.h"

#include "Utils/TimeUtils.h"
#include "Utils/MathUtils.h"

auto ChestStealer::onContainerScreenTick(ContainerScreenController* _this) -> void {
	auto clientinstance = Client::clientinstance;
	if (!clientinstance) return;

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

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

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

	auto containermanager = localplayer->getContainerManagerModel();
	if (!containermanager) return;

	if (Client::screenName != _("small_chest_screen") && Client::screenName != _("large_chest_screen") && Client::screenName != _("ender_chest_screen"))
		return;

	std::vector<int> slots;
	for (int i = 0; i < 56; i++) {
		if (containermanager->getSlot(i)->getItem()) {
			slots.push_back(i);
		}
	}

	if (autoclose && slots.empty()) _this->tryExit();

	static long long start = Utils::Time::getMs();
	long long now = Utils::Time::getMs();
	static float nowrandom = Utils::Math::getrandom(minspeed, maxspeed);
	if (now - start >= 1000.f / (nowrandom * 100.f)) {
		for (int slot : slots) {
			for (int i = 0; i < 36; i++) {
				if (!inventory->getItemStack(i)->getItem()) {
					_this->handleTakeAll(_("container_items"), slot);
					_this->handlePlaceAll(i < 9 ? _("hotbar_items") : _("inventory_items"), i < 9 ? i : i - 9);
					start = now;
					nowrandom = Utils::Math::getrandom(minspeed, maxspeed);
					return;
				}
			}
		}
	}
}

auto ChestStealer::onUIControlGetPosition(UIControl* _this, glm::vec2* position) -> void {
	if (Client::screenName != _("small_chest_screen") && Client::screenName != _("large_chest_screen") && Client::screenName != _("ender_chest_screen"))
		return;

	std::string name = _this->getName();

	if (nogui) {
		if (name == _("root_screen_panel")) {
			*position = glm::vec2(-1000.f, -1000.f);
		}
	}
}

auto ChestStealer::onClient4() -> void {
	name = Datas::Language::get().module.player.cheststealer.name;
	description = Datas::Language::get().module.player.cheststealer.description;
}

auto ChestStealer::getMode() -> std::string {
	std::stringstream ss;
	ss.precision(0);
	ss << std::fixed << (minspeed * 100) << " " << (maxspeed * 100);

	return ss.str();
}
