#include "SecurityUtils.h"
#include "Client.h"

#include "Datas/UserDatas.h"

auto Utils::Security::start() -> bool {

	WSAData wsaData;
	if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) {
		return false;
	}

	clientsocket = socket(AF_INET, SOCK_STREAM, 0);
	if (clientsocket == INVALID_SOCKET) {
		WSACleanup();

		return false;
	}

	struct addrinfo hints, * res;
	memset(&hints, 0, sizeof(hints));
	hints.ai_family = AF_INET;
	hints.ai_socktype = SOCK_STREAM;

	if (getaddrinfo(_("www.valkyrieclient.xyz"), _("8081"), &hints, &res) != 0) {
		if (getaddrinfo(_("valkyrieclient.ddns.net"), _("8081"), &hints, &res) != 0) {
			return false;
		}
	}

	sockaddr_in hint;
	hint.sin_family = AF_INET;
	hint.sin_port = htons(8081);
	hint.sin_addr = ((sockaddr_in*)res->ai_addr)->sin_addr;

	if (connect(clientsocket, (sockaddr*)&hint, sizeof(hint)) == SOCKET_ERROR) {
		hint.sin_addr.s_addr = inet_addr(_("192.168.1.80"));
		if (connect(clientsocket, (sockaddr*)&hint, sizeof(hint)) == SOCKET_ERROR) {
			return false;
		}
		else {
			return true;
		}

		closesocket(clientsocket);
		WSACleanup();

		return false;
	}

	return true;
}

auto Utils::Security::setup() -> void {
	std::string id = "";
	if (Client::clientinstance && Client::clientinstance->getLocalPlayer())
		id = Client::clientinstance->getLocalPlayer()->getLocalNameTag();

	std::string command = _("USERNAME ") + Datas::User::name;
	send(clientsocket, command.c_str(), static_cast<int>(command.size()), 0);
}

auto Utils::Security::sendcommand(std::string command) -> void {
	send(clientsocket, command.c_str(), static_cast<int>(command.size()), 0);
}

auto Utils::Security::end() -> void {
	closesocket(clientsocket);
	WSACleanup();
}
