#include "StaffDetector.h"
#include "Client.h"

#include "Utils/PlayerUtils.h"
#include "Utils/ChatUtils.h"

auto StaffDetector::onClient3() -> void {
	auto clientinstance = Client::clientinstance;
	if (!clientinstance) return;

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

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

    if (!enabled) return;

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

	std::vector<std::wstring> list;
	level->forEachPlayer([&](Player& player) {
		if (Utils::Players::isRealPlayer(&player)) {
			list.push_back(Utils::String::toWstring(Utils::String::removeSymbols((&player)->getNameTag())));
		}

		return true;
		});

    HINTERNET hSession = WinHttpOpen(L"HiveClient/1.0", WINHTTP_ACCESS_TYPE_DEFAULT_PROXY, WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0);
    if (!hSession) return;

    HINTERNET hConnect = WinHttpConnect(hSession, L"api.playhive.com", INTERNET_DEFAULT_HTTPS_PORT, 0);

    if (!hConnect) {
        WinHttpCloseHandle(hSession);
		return;
    }


    bool detect = false;
    std::string staffname;
	for (const auto& player : list) {
       std::wstring path = L"/v0/game/all/main/" + player;

        HINTERNET hRequest = WinHttpOpenRequest(hConnect, L"GET", path.c_str(), nullptr, WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES, WINHTTP_FLAG_SECURE);
        if (!hRequest) continue;

        BOOL bResults = WinHttpSendRequest(hRequest, WINHTTP_NO_ADDITIONAL_HEADERS, 0, WINHTTP_NO_REQUEST_DATA, 0, 0, 0);
        if (bResults) bResults = WinHttpReceiveResponse(hRequest, nullptr);

        std::string result;

        if (bResults) {
            DWORD dwSize = 0;
            do {
                DWORD dwDownloaded = 0;
                WinHttpQueryDataAvailable(hRequest, &dwSize);
                if (dwSize == 0)
                    break;

                std::string buffer(dwSize, 0);
                WinHttpReadData(hRequest, buffer.data(), dwSize, &dwDownloaded);
                result.append(buffer.data(), dwDownloaded);
            } while (dwSize > 0);
        }

        WinHttpCloseHandle(hRequest);

        if (!Client::running) return;
        if (!result.empty()) {
            try {
                nlohmann::json data = nlohmann::json::parse(result);
                const auto& main = data[_("main")];
                if (main.contains(_("rank"))) {
                    if (main[_("rank")] == _("HIVE_TEAM")) {
                        detect = true;
                        staffname = Utils::String::toString(player);
                        break;
                    }
                }
            }
            catch (const std::exception& e) {
            }
        }
	}

    if (detect) {
        Utils::Chat::display(_("Staff detected: ") + staffname);
    }
}
