#include "AutoClicker.h"
#include "Client.h"

#include "Utils/TimeUtils.h"

auto AutoClicker::onClient() -> void {
	for (Setting* setting : Client::findSetting(this, _("Left Cps"))) {
		setting->visible = left;
	}
	for (Setting* setting : Client::findSetting(this, _("Right Cps"))) {
		setting->visible = right;
	}

	if (!enabled) return;
	if (Client::screenName != _("hud_screen")) return;

	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;

	if (!Client::mouseptr) return;

	static auto func = reinterpret_cast<void(__fastcall*)(void*, char, char, short, short, short, short, char)>(Client::mouseptr);

	long long now = Utils::Time::getMs();
	static long long lstart = now, rstart = now;
	if (left && leftclicking) {
		if (now - lstart >= 1000.f / leftcps) {
			if (onlysword) {
				auto itemstack = inventory->getItemStack(playerinventory->getHandSlot());
				if (itemstack->getItem()) {
					auto item = *itemstack->getItem();
					if (item->getName().find(_("_sword")) == std::string::npos) {
						return;
					}
				}
			}

			func(Client::mousecontroller, 1, 0, Client::mousex, Client::mousey, Client::mousemovx, Client::mousemovy, 2);
			func(Client::mousecontroller, 1, 1, Client::mousex, Client::mousey, Client::mousemovx, Client::mousemovy, 2);

			lstart = now;
		}
	}
	if (right && rightclicking) {
		if (now - rstart >= 1000.f / rightcps) {
			auto itemstack = inventory->getItemStack(playerinventory->getHandSlot());
			if (itemstack->getItem()) {
				auto item = *itemstack->getItem();
				if (nobow && item->getName() == _("bow")) {
					return;
				}

				if (nofood && item->isFood()) {
					return;
				}

				if (item->getName().find(_("_sword")) != std::string::npos) {
					return;
				}
			}

			func(Client::mousecontroller, 2, 0, Client::mousex, Client::mousey, Client::mousemovx, Client::mousemovy, 2);
			func(Client::mousecontroller, 2, 1, Client::mousex, Client::mousey, Client::mousemovx, Client::mousemovy, 2);

			rstart = now;
		}
	}
}

auto AutoClicker::onMouse(char button, char action, bool* cancel) -> void {
	if (button == 1) {
		leftclicking = static_cast<int>(action) == 1;
	}
	if (button == 2) {
		rightclicking = static_cast<int>(action) == 1;
	}
}
