#include "RichPresence.h"

#include "Client.h"

#include "Utils/TimeUtils.h"

auto RichPresence::onClient() -> void {
	name = Datas::Language::get().module.other.richpresence.name;
	description = Datas::Language::get().module.other.richpresence.description;

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

	if (now - start < 1000.f) return;
	else
		start = now;

	std::ofstream file_out(Utils::File::getTempState() + _("\\RPC.txt"));
	if (!file_out) return;

	std::string detail = _("Not joined server");
	auto clientinstance = Client::clientinstance;
	if (clientinstance) {
		if (clientinstance->getLocalPlayer()) {
			auto loopbackpacketsender = clientinstance->getLoopbackPacketSender();
			if (loopbackpacketsender) {
				auto networksystem = loopbackpacketsender->getNetworkSystem();
				if (networksystem) {
					auto remoteconnectorcomposite = networksystem->getRemoteConnectorComposite();
					if (remoteconnectorcomposite) {
						auto raknetconnector = remoteconnectorcomposite->getRakNetConnector();
						if (raknetconnector) {
							detail = raknetconnector->getJoinedIP();
							if (detail.find(_(".")) == std::string::npos) {
								detail = _("Local World");
							}
						}
					}
				}
			}
		}
		else if (enabled) {
			detail = _("  ");
		}
	}

	if (!enabled)
		detail = _("");

	file_out << detail;
	file_out.close();
}

auto RichPresence::onDisabled() -> void {
	std::ofstream file_out(Utils::File::getTempState() + _("\\RPC.txt"));
	if (!file_out) return;

	file_out << _("");
	file_out.close();
}
