
#include <iostream>
using namespace std;
#include "Client_Server.h"
#include "Client.h"
#include "Server.h"


#include<ctime>
Miracl precision(1000,10); // This makes sure that MIRACL

//header file containing the class definition



/*--------------------- Client Constructor ---------*/
	Client_Server::Client_Server()//takes no argument
	{
		if (WSAStartup(MAKEWORD(1, 1), &wsaData) != 0)
		//used to initialise ws2_32.dll for later use
		{
		        cout << "WSAStartup failed";
		        exit(1);//if this does not work exit the program
		}
		
		sockfd = (int) socket(AF_INET, SOCK_STREAM , 0);
		//initialising the socket
//Stream sockets are reliable two way connected communication stream,
//as they use TCP.

		len = 1500;
		//setting the length of the buffer 
		data_received = new char[len];
//creating a character array to store the data received from the recv() method.

	
	}

/*---------------------- End Client Constructor ------------------------------*/

/*------------------- Destructor --------------------------------------*/
	Client_Server::~Client_Server()
	//This is the destructor which ties up all the 
	{
		//depending on the value of is_server(true or false)
		//the relevant sockets are shutdown
		if(is_server)
		{

			int shutdown_sockfd = shutdown(sockfd,2); 
			int shutdown_new_fd = shutdown(new_fd,2);
						
		}
		else
			int shutdown_sockfd = shutdown(sockfd,2);//shut client socket.
		delete data_received;
		WSACleanup();//cleans up ws2_32.dll
	}
/*--------------------End of Destructor--------------------------*/



	//--- checks whether the server or client is called
	//is used to determine the actions taken in the destructor
	bool Client_Server::isServer()
	{
		if(is_server==true)
			return true;
		else
			return false;
	}//end programType.
	


	//---- Sends data using the socket options, uses socket variable global socket.
	bool Client_Server::send_data(char msg[])
	{
		int number_bytes = (int) strlen(msg);//number of bytes in message.
	
		int bytes_sent = send(global_socket, msg, len, 0);
		//If the number of bytes of the message is less than the number sent, not all the message has been sent.
		if(number_bytes <= bytes_sent)
			return true;
		else
			return false;

	}//end send_data(char msg[])
	

	//---- Receives data using the socket calls
	bool Client_Server::recv_data()
	{
		memset(data_received,0,len);//set all of memory pointed to by data_received to be equal to 0
		// so that when this function is call more than once, old data will not interfer with new data.
		int num_bytes_got = recv(global_socket,data_received,len,0);
		//if data is received in error
		if(num_bytes_got == 0 || num_bytes_got == -1)
		{
			return false;	
		}
		else
			return true;
	}//end receive data

	char * Client_Server::getRecvData()
	{
		return data_received;
	}

