// asteroid.cpp: Beispielspieler für bobjects 
// Harald Bögeholz / c't

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>

#include <winsock2.h>

#include "player.h"


int main(int argc, char* argv[])
{
	if (argc != 2)
	{
		fprintf(stderr, "Aufruf: asteroid <IP-Adresse>\n");
		exit(1);
	}
	unsigned long server_ip = inet_addr(argv[1]);
	if (server_ip == INADDR_NONE)
	{
		fprintf(stderr, "Ungueltige IP-Adresse: '%s'\n", argv[1]);
		exit(1);
	}

	WSADATA wsadata;
	if (WSAStartup(MAKEWORD(2,2), &wsadata))
	{
		fprintf(stderr, "Fehler beim Initialisieren von Winsock.\n");
		exit(2);
	}


	SOCKET sd;
	sd = socket(AF_INET, SOCK_DGRAM, 0);
	if (sd == INVALID_SOCKET)
	{
		fprintf(stderr, "Fehler %d bei socket().\n", WSAGetLastError());
		exit(2);
	}

	unsigned long enable_nonblocking = 1;
	if (ioctlsocket(sd, FIONBIO, &enable_nonblocking))
	{
		fprintf(stderr, "Kann Socket nicht auf nonblocking setzen (%d)", WSAGetLastError());
		exit(1);
	}

	sockaddr_in sa;
	memset(&sa, 0, sizeof sa);
	sa.sin_family = AF_INET;
	sa.sin_addr.s_addr = 0;
	sa.sin_port = 0;

	if (bind(sd, (struct sockaddr*) &sa, sizeof sa))
	{
		fprintf(stderr, "Fehler %d bei bind().\n", WSAGetLastError());
		exit(2);
	}

	Player player(sd, server_ip);
	player.Run();

	return 0;
}
