#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <netdb.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <arpa/inet.h>


int getData( int sockfd ) {
	//declare variable, create a buffer to store the received information
	char buffer[32];
	int n;

	//read information from the server 
	n = read(sockfd,buffer,31);

	//append an exit character at the end of the message
	buffer[n] = '\0';
	//return the message to the main program
	return atoi( buffer );
}

int main(int argc, char *argv[])
{
	//declare variables
    int sockfd, portno = 51717, n;
	//hardcode IP address of server
    char serverIp[] = "100.65.7.82";
    struct sockaddr_in serv_addr;
    struct hostent *server;
    char buffer[256];
    int count;

	//loop forever
	while(1){
		//set socket options
		sockfd = socket(AF_INET, SOCK_STREAM, 0) ; 

		//set the server IP address
		server = gethostbyname( serverIp );

		//clear a buffer for the server address information
		bzero( (char *) &serv_addr, sizeof(serv_addr));
		//set the necessary options and copy the information obtained from the host name
		serv_addr.sin_family = AF_INET;
		bcopy( (char *)server->h_addr, (char *)&serv_addr.sin_addr.s_addr, server->h_length);
		serv_addr.sin_port = htons(portno);

		//send connection request and confirmation to the server
		connect(sockfd,(struct sockaddr *)&serv_addr,sizeof(serv_addr));
			
		//read the count from the server, this is a blocking function and the program will not proceed without input from the server
		count = getData(sockfd);
		//if the count is greater than zero print the message
		if(count > 0){
			//let the user know the light is on and what the current count is
			printf("current count: %d -> the light is on.\n", count);
			//close the socket connection
			close(sockfd);
			//allow time for the connection to close 
			sleep(3);
		}
		//if the count is equal to zero print the message
		else if(count == 0){
			//inform the user that the light is off and what the current count is
			printf("current count: %d -> the light is off.\n", count);
			//close the socket connection
			close(sockfd);
			//allow time for the connection to close
			sleep(3);
		}
	}
	return 0;
}