#include "blitz/network/Network.h"

namespace blitz {
namespace network {

class NetworkInitializer {
  public:
	NetworkInitializer();
	~NetworkInitializer();

	NetworkInitializer(const NetworkInitializer& rhs) = delete;
	NetworkInitializer& operator=(const NetworkInitializer& rhs) = delete;
};

#ifdef _WIN32
NetworkInitializer::NetworkInitializer() {
	WSADATA wsaData;
	WSAStartup(MAKEWORD(2, 2), &wsaData);
}
NetworkInitializer::~NetworkInitializer() {
	WSACleanup();
}
#else
NetworkInitializer::NetworkInitializer() {}
NetworkInitializer::~NetworkInitializer() {}
#endif

NetworkInitializer initializer;

IPAddresses Dns::Resolve(const std::string& host) {
	IPAddresses list;
	addrinfo hints{};
	addrinfo* addresses = nullptr;

	hints.ai_family = AF_INET;
	hints.ai_socktype = SOCK_STREAM;
	hints.ai_protocol = IPPROTO_TCP;

	getaddrinfo(host.c_str(), NULL, &hints, &addresses);

	for (addrinfo* p = addresses; p != NULL; p = p->ai_next) {
#ifdef _WIN32
		char* straddr = inet_ntoa(((sockaddr_in*)p->ai_addr)->sin_addr);
#else
		char straddr[512];

		inet_ntop(p->ai_family, &(reinterpret_cast<sockaddr_in*>(p->ai_addr))->sin_addr, straddr, sizeof(straddr));
#endif

		list.push_back(IPAddress(straddr));
	}

	return list;
}

}  // namespace network
}  // namespace blitz
