// Hlavicka pro sitovou komunikaci

#include <winsock.h>
#include <iostream>
#include <string>

#define BUFSIZE 4096

WORD wVersionRequested = MAKEWORD(1,1); // Cislo verze
WSADATA data;                           // Struktura s info. o knihovne
SOCKET mySocket;
sockaddr_in serverSock;                 // Vzdaleny "konec potrubi"
std::string gRobotName = "";
std::string gConnectionAddress = "";
int gConnectionPort = 0;
hostent * gConnectionHost;

void setConnection();

bool connectionIsInitialize()
{
	return false;
}

std::string sendStringToServer(std::string const & value)
{
	if (send(mySocket, value.c_str(), value.size()+1, 0) == -1)
	{
		std::cerr << "Problém s odesláním dat" << std::endl;
		WSACleanup();
		return false;
	}
	int size = -1;
	char buf[BUFSIZE];
	std::string text = "";
	//while ((size != 0) && (size != -1))
	//{
		size = recv(mySocket, buf, BUFSIZE, 0);
		text.append(buf, buf + size);
	//}
	if (size == -1)
	{
		std::cerr << "Nelze přijmout data" << std::endl;
	}
	return text;
}

std::string sendMessageToServer(std::string const & type, std::string const & value)
{
	std::string text = type + "\n" + value;
	text = sendStringToServer(text);
	return text;
}

bool startClient()
{
	if(gRobotName == "")
	{
		std::cout << "Zadejte jmeno robota:" << std::endl;
		getline( std::cin, gRobotName, '\n' );
	}
	if(gConnectionAddress == "")
	{
		std::cout << "Zadejte nazev serveru:" << std::endl;
		getline( std::cin, gConnectionAddress, '\n' );
	}
	if(gConnectionPort == 0)
	{
		std::cout << "Zadejte komunikacni port:" << std::endl;
		std::cin >> gConnectionPort;
	}

	if (WSAStartup(wVersionRequested, &data) != 0)
	{
		std::cerr << "Nepodařilo se inicializovat sokety" << std::endl;
		return false;
	}
	if ((gConnectionHost = gethostbyname(gConnectionAddress.c_str())) == NULL)
	{
		std::cerr << "patná adresa" << std::endl;
		WSACleanup();
		return false;
	}
	if ((mySocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) == -1)
	{
		std::cerr << "Nelze vytvořit soket" << std::endl;
		WSACleanup();
		return false;
	}
	serverSock.sin_family = AF_INET;
	serverSock.sin_port = htons(gConnectionPort);
	memcpy(&(serverSock.sin_addr), gConnectionHost->h_addr, gConnectionHost->h_length);
	if (connect(mySocket, (sockaddr *)&serverSock, sizeof(serverSock)) == -1)
	{
		std::cerr << "Nelze navázat spojení" << std::endl;
		WSACleanup();
		return false;
	}

	while( sendMessageToServer("connect",gRobotName) == "0" )
	{
		std::cout << "K serveru je jiz pripojen stejnojmenny robot." << std::endl << "Zadejte jine jmeno robota:" << std::endl;
		getline( std::cin, gRobotName, '\n' );
	}
	std::cout << "Connected to server..." << std::endl;
	return true;
}

bool endClient()
{
	sendMessageToServer("finish","");
	closesocket(mySocket);
	WSACleanup();
	std::cout << "Disconnected from server..." << std::endl;
	return true;
}