/**
 * \file ServerSocket.cpp
 *
 * Implementation of the ServerSocket class
 */

#include "Common/Protocol/ServerSocket.h"
#include "Common/Tasks.h"
#include "Common/Support/Debug.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#ifdef WIN32
	#include <winsock.h>
#else	// WIN32
	#include <sys/types.h>
	#include <sys/time.h>
	#include <sys/socket.h>
	#include <netinet/in.h>
	#include <unistd.h>
	#include <netdb.h>
	#include <arpa/inet.h>
#endif	// WIN32


/// Connection timeout in seconds
#define TIMEOUT 10

ServerSocket::ServerSocket()
	: Module("ServerSocket", "ServerSocket module", "v0.1.005"),
	  parser(NULL), connected(false), sock(0)
{
#ifdef WIN32
	WORD ver = MAKEWORD( 1, 1 );
	WSADATA wsaData;
	if(WSAStartup(ver, &wsaData) != 0) perror("WSAStartup failed");
#endif	// WIN32

	sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);

#ifdef WIN32
	unsigned long tmp = 0;
	ioctlsocket(sock, FIONBIO, &tmp);
#endif	// WIN32*/

	sockaddr_in cli_addr;
	cli_addr.sin_family = AF_INET;
	cli_addr.sin_port = htons(0);
	cli_addr.sin_addr.s_addr = htonl(INADDR_ANY);
	bind(sock, (sockaddr*) &cli_addr, sizeof(cli_addr));

	memset(&address, 0, sizeof(address));
	address.sin_family = AF_INET;

	Main::GetInstance()->RegisterModule(this, COMMUNICATION_TASK);
}

ServerSocket::~ServerSocket()
{
#ifdef WIN32
	closesocket(sock);
	WSACleanup();
#else	// WIN32
	close(sock);
#endif	// WIN32
}

int ServerSocket::Init(int argc, char** argv, int)
{
	parser = (MsgProcessInterface*) Main::GetInstance()->GetInterface(MESSAGE_PROCESS_TASK);
	if(parser == NULL) return INIT_ERR;
    // GP
//	clangparser = (MsgProcessInterface*) Main::GetInstance()->GetInterface(CLANG_MESSAGE_PROCESS_TASK);
//	if(clangparser == NULL) return INIT_ERR;

	return INIT_OK;
}

void ServerSocket::Run(int)
{
	int status = ReceiveMsg();
	//test ci spadol server
	if(status && connected)
	{
		ERRN("Server is down!");
		Disconnect("(bye)");
		Main::GetInstance()->ShutDown();
	}
}

int ServerSocket::SetServer(const char* addr, unsigned port)
{
	struct hostent* host = gethostbyname(addr);

	if(host == NULL)
	{
		if(inet_addr(addr) == INADDR_NONE) return 1;	// error
	}
	else
	{
		addr = inet_ntoa(*(struct in_addr*) *host->h_addr_list);
	}

	address.sin_port = htons(port);
	address.sin_addr.s_addr = inet_addr(addr);

	return 0;
}

int ServerSocket::Connect(const char* msg)
{
	connected = true;
	return SendMsg(msg);
}

int ServerSocket::SendMsg(const char* msg)
{
	if(!connected) return 1;	// error, not "connected"

	int rval = sendto(sock, msg, strlen(msg) + 1, 0, (sockaddr*) &address, sizeof(address));
	if(rval <= 0) return 1;		// error

//	DBGN("SEND: %s", msg);

	return 0;
}

int ServerSocket::ReceiveMsg()
{
	if(!connected)
	{
		// Error, not "connected"
#ifdef WIN32
		_sleep(10);
#else	// WIN32
		usleep(10000);
#endif	// WIN32
		return 1;
	}

#ifdef WIN32
	int fromlen = sizeof(address);
#else	// WIN32
	socklen_t fromlen = sizeof(address);
#endif	// WIN32

	struct timeval timeout;
	timeout.tv_sec = TIMEOUT;
	timeout.tv_usec = 0;

	fd_set sockset; FD_ZERO(&sockset); FD_SET(sock, &sockset);
	
	if(select(sock + 1, &sockset, NULL, NULL, &timeout) < 0)
	{
		message[0] = 0;
		return 1;				// error
	}

	if (!FD_ISSET(sock, &sockset))
	{
		message[0] = 0;
		return 1;				// error, timeout
	}

	int rval = recvfrom(sock, message, BUFFERSIZE - 1, 0, (sockaddr*) &address, &fromlen);
	
	if(rval <= 0)
	{
		// Chyba pri prijimani
		message[0] = 0;
		return 1;				// error
	}

	// Prijatie uspesne
	message[rval] = 0;	// dam na koniec 0 (ukoncenie retazca)

	//DBGN("RECV: %s", message);

	// Parsujeme spravu
	if(parser->ParseMsg(message) != 0)
	{
        // GP
//        if(clangparser->ParseMsg(message) != 0)
 		  WARNN("could not parse server message %s", message);
	}

	return 0;
}

int ServerSocket::Disconnect(const char* msg)
{
	if(SendMsg(msg)) return 1;
	connected = false;

	return 0;
}

Interface* ServerSocket::GetInterface(int task) const
{
	return (CommunicationInterface*) this;
}

