#include <iostream>
using namespace std;
#include "Server.h"

#include<ctime>


//header file containing the class definition

/*----------------------Server Constructor-------------------------------*/
Server::Server(int Port_Number): Client_Server()//takes one argument
	{

		is_server = true;//used to determine actions taken in the destructor
			//insert address information into the my_addr struct
			my_addr.sin_family = AF_INET;  //Settin the Address family        
			my_addr.sin_port = htons(Port_Number);     
			// Convert Port_Number into Network Byte Order.
			my_addr.sin_addr.s_addr = INADDR_ANY;
			//enables the server to listen for connections from any IP Address
			memset(&(my_addr.sin_zero), '\0', 8); // zero the rest of the struct 

			
			bind(sockfd, (struct sockaddr *)&my_addr, sizeof(struct sockaddr));
			// Bind the socket to our local server address
			int sin_size = sizeof(struct sockaddr_in);
			if(listen(sockfd,5)== -1)
			//listens to the socket for any connections, return -1 on error.
			{
				cout <<"Error listening to port "<<endl;
				exit(1);
			}
			new_fd = (int) accept(sockfd, (struct sockaddr *)&their_addr, &sin_size);
			//if connection is made then the server will accept the connection 
			//and return a new socket file descriptor.
			if(new_fd == -1)//socket is -1 on error.
			{
				cout <<"Problem accepting connection, enter a number to exit."<<endl;
				exit(1);
			}

			global_socket = new_fd;
			//this enables all functions to access this received socket file, 
			// with out worrying if it is a server or a client
	
	}
/*---------------- End of Server Constructor --------------------------*/
	/*------------------- Destructor --------------------------------------*/
	/*Server::~Server()
	//This is the destructor which ties up all the 
	{
		//Client_Server::~Client_Server();
		
	}*/
/*--------------------End of Destructor--------------------------*/



	//--- checks whether the server or client is called
	//is used to determine the actions taken in the destructor
	bool Server::isServer()
	{
		if(Client_Server::isServer())
			return true;
		else
			return false;
		
	}//end 
	


	//---- Sends data using the socket options, uses socket variable global socket.
	bool Server::send_data(char msg[])
	{
		if(Client_Server::send_data(msg))
			return true;
		else
			return false;
	}//end send_data(char msg[])
	

	//---- Receives data using the socket calls
	bool Server::recv_data()
	{
		if(Client_Server::recv_data())
			return true;
		else
			return false;
	}//end receive data

	char * Server::getRecvData()
	{
		return (Client_Server::getRecvData());
		
	}

