#include "NetSkip.h"
#include "Client.h"

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

auto NetSkip::onRunUpdateCycle(bool* cancel) -> void {
	if (silent) return;

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

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

	if (!firstGet) {
		lastpos = Utils::Move::getPosition(localplayer);
		firstGet = true;
	}

	long long now = Utils::Time::getMs();
	static long long start = now;
	if (now - start >= 100.f * amount) {
		lastpos = Utils::Move::getPosition(localplayer);
		*cancel = false;
		start = now;
	}
	else {
		*cancel = true;
	}
}

auto NetSkip::onRenderActorBefore(Actor* actor, glm::vec3* camera, glm::vec3* position) -> void {
	if (render)
		*position = *position - *camera - *position + lastpos;
}

auto NetSkip::onWorldTick(Player* _this) -> void {
	if (!silent) return;

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

	auto loopbackpacketsender = clientinstance->getLoopbackPacketSender();
	if (!loopbackpacketsender) return;

	if (!firstGet) {
		lastpos = Utils::Move::getPosition(_this);
		firstGet = true;
	}

	if (send) {
		lastpos = Utils::Move::getPosition(_this);
		/*
		for (Packet* packet : packets) {
			loopbackpacketsender->sendToServer(packet);
		}*/
		packets.clear();
		send = false;
	}
}

auto NetSkip::onPacketSendAfter3(Packet* packet, bool* cancel) -> void {
	if (!silent) return;

	if (packet->getID() != PacketID::PlayerAuthInput) return;

	long long now = Utils::Time::getMs();
	static long long start = now;
	if (now - start >= 100.f * amount) {
		send = true;
		start = now;
	}
	else {
		packets.push_back(packet);
		*cancel = true;
	}
}

auto NetSkip::onDisabled() -> void {
	firstGet = false;
}
