/*
 * the thread for the server
 */


#ifdef MAC_OS

/*
 * the server thread
 */
void *runServerThread(void *portid)
{
  int BUFFER_SIZE=1024;                    // maximum network message size
  int DEFAULT_PORT=2000;                   // our port
  char buffer[BUFFER_SIZE];                // the message buffer (input)
  char outputBuffer[BUFFER_SIZE];          // the output buffer
  unsigned int sockfd, newsockfd, clilen;  // network variables
  struct sockaddr_in serv_addr, cli_addr;  // network configuration
  int n;
  
  memset(buffer,0,BUFFER_SIZE);  // clear out the network message buffer
  memset((char *) &serv_addr, 0, sizeof(serv_addr)); // clear serv_addr
  
  sockfd = socket(AF_INET, SOCK_STREAM, 0);
  if (sockfd < 0) printf("ERROR opening socket");
  
  serv_addr.sin_family = AF_INET;         // parameters to bind to port
  serv_addr.sin_addr.s_addr = INADDR_ANY;
  serv_addr.sin_port = htons(DEFAULT_PORT);
  if (bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0) 
    printf("ERROR on binding\n");  
  
  printf("Server listening on port %d.\n", DEFAULT_PORT);
  listen(sockfd,1);          // no need to wait for more than 1 connection!
  clilen = sizeof(cli_addr); // needed for the call to accept
  
  /*
   * this loop allows it to connect to clients repeatedly via the call to accept
   */
  while (!timeToQuitNow) // in case the main thread shuts the server down
  {
    
    /*
     * this next call (to accept) blocks
     */
    newsockfd = accept(sockfd, (struct sockaddr *) &cli_addr, &clilen);
    printf("Server accepted a connection... .\n");
    
    if (newsockfd < 0) printf("ERROR on accept");
    
    /*
     * conversation with this client...
     */
    while (!timeToQuitNow) // in case the main thread shuts the server down
    {
      /*
       * read in the message
       */
      n = read(newsockfd,buffer,BUFFER_SIZE-1); // trailing zero
      if (n < 0) 
      {
        printf("Error reading from socket, n = %d\n", n);
        break;
      }
      buffer[n]=0;
      printf("The server received the message: %s\n",buffer);
      
      if (strncmp(buffer,"quit",4) == 0)   // we can shut everything down from here
      {
        timeToQuitNow = 1;    // tell the other thread to quit, too!
        printf("Received a shutdown message from the client.\n");
        snprintf(outputBuffer,BUFFER_SIZE-1,"quit");
        n = write(newsockfd, outputBuffer, strlen(outputBuffer));
      }
      
      else if (strncmp(buffer,"A ",2) == 0)   // looking for an "A " message
      {
        sscanf(buffer, "A %d", &runAlgorithm);
        printf("Setting runAlgorithm to %d.\n", runAlgorithm);
        snprintf(outputBuffer,BUFFER_SIZE-1,"%s",buffer); // send the message back
        n = write(newsockfd, outputBuffer, strlen(outputBuffer));
      }
      
	/*  else if (strncmp(buffer,"B",1) == 0)  //looking for a "B" message
	  {
		sscanf(buffer, "B");
		printf("I saw a capital B.\n");
		nextFileNumber = nextFileNumber - 2;
		if (nextFileNumber < 0) nextFileNumber = MAX_FILE_NUMBER;
		captureStatus = ONEFRAME;
		runAlgorithm=true;
		snprintf(outputBuffer,BUFFER_SIZE-1,"%s",buffer); // send the message back
        n = write(newsockfd, outputBuffer, strlen(outputBuffer));
	  }*/
      
      else if (strncmp(buffer,"R1",2) == 0)   // looking for an "Robot" message
      {
		//for (int j=0; j<8 ; j++)
		//{
			//sscanf(buffer, "R %d", &runAlgorithm);
			printf("I saw a capital R1.\n");
			int x,y;
			// send over the # of messages (blobs) to be sent
			// loop through and send each of the blob pieces of data
			x = snprintf(outputBuffer,BUFFER_SIZE-1,"%d ",24); // send the value back
			for (int i=0 ; i<3 ; ++i)
			{
				y = snprintf(outputBuffer+x,BUFFER_SIZE-1,"%d %d %d %d %d ",colorData[0].xmin[i],
						colorData[0].xmax[i],colorData[0].ymin[i],colorData[0].ymax[i],
						colorData[0].colour); // send the value back
				x = x + y; // x is the offset into the string
				// y is the amount of bytes just printed...
				if (x > BUFFER_SIZE-1) break;
			}
			printf("returning %s.\n", outputBuffer); 
			n = write(newsockfd, outputBuffer, strlen(outputBuffer));
		//}
      }
	  
	  
	  else if (strncmp(buffer,"R2",2) == 0)   // looking for an "Robot" message
      {
        //sscanf(buffer, "R %d", &runAlgorithm);
        printf("I saw a capital R2.\n");
		int x,y;
		// send over the # of messages (blobs) to be sent
		// loop through and send each of the blob pieces of data
		x = snprintf(outputBuffer,BUFFER_SIZE-1,"%d ",24); // send the value back
		for (int i=0 ; i<3 ; ++i)
		{
			y = snprintf(outputBuffer+x,BUFFER_SIZE-1,"%d %d %d %d %d ",colorData[1].xmin[i],
						colorData[1].xmax[i],colorData[1].ymin[i],colorData[1].ymax[i],
						colorData[1].colour); // send the value back
			x = x + y; // x is the offset into the string
			// y is the amount of bytes just printed...
			if (x > BUFFER_SIZE-1) break;
		}
		printf("returning %s.\n", outputBuffer);
		n = write(newsockfd, outputBuffer, strlen(outputBuffer));
      }
	  
	  else if (strncmp(buffer,"R3",2) == 0)   // looking for an "Robot" message
      {
        //sscanf(buffer, "R %d", &runAlgorithm);
        printf("I saw a capital R3.\n");
		int x,y;
		// send over the # of messages (blobs) to be sent
		// loop through and send each of the blob pieces of data
		x = snprintf(outputBuffer,BUFFER_SIZE-1,"%d ",24); // send the value back
		for (int i=0 ; i<3 ; ++i)
		{
			y = snprintf(outputBuffer+x,BUFFER_SIZE-1,"%d %d %d %d %d ",colorData[2].xmin[i],
						colorData[2].xmax[i],colorData[2].ymin[i],colorData[2].ymax[i],
						colorData[2].colour); // send the value back
			x = x + y; // x is the offset into the string
			// y is the amount of bytes just printed...
			if (x > BUFFER_SIZE-1) break;
		}
		printf("returning %s.\n", outputBuffer);
		n = write(newsockfd, outputBuffer, strlen(outputBuffer));
      }
	  
	  else if (strncmp(buffer,"R4",2) == 0)   // looking for an "Robot" message
      {
        //sscanf(buffer, "R %d", &runAlgorithm);
        printf("I saw a capital R4.\n");
		int x,y;
		// send over the # of messages (blobs) to be sent
		// loop through and send each of the blob pieces of data
		x = snprintf(outputBuffer,BUFFER_SIZE-1,"%d ",24); // send the value back
		for (int i=0 ; i<3 ; ++i)
		{
			y = snprintf(outputBuffer+x,BUFFER_SIZE-1,"%d %d %d %d %d ",colorData[3].xmin[i],
						colorData[3].xmax[i],colorData[3].ymin[i],colorData[3].ymax[i],
						colorData[3].colour); // send the value back
			x = x + y; // x is the offset into the string
			// y is the amount of bytes just printed...
			if (x > BUFFER_SIZE-1) break;
		}
		printf("returning %s.\n", outputBuffer);
		n = write(newsockfd, outputBuffer, strlen(outputBuffer));
      }
	  
	  else if (strncmp(buffer,"R5",2) == 0)   // looking for an "Robot" message
      {
        //sscanf(buffer, "R %d", &runAlgorithm);
        printf("I saw a capital R5.\n");
		int x,y;
		// send over the # of messages (blobs) to be sent
		// loop through and send each of the blob pieces of data
		x = snprintf(outputBuffer,BUFFER_SIZE-1,"%d ",24); // send the value back
		for (int i=0 ; i<3 ; ++i)
		{
			y = snprintf(outputBuffer+x,BUFFER_SIZE-1,"%d %d %d %d %d ",colorData[4].xmin[i],
						colorData[4].xmax[i],colorData[4].ymin[i],colorData[4].ymax[i],
						colorData[4].colour); // send the value back
			x = x + y; // x is the offset into the string
			// y is the amount of bytes just printed...
			if (x > BUFFER_SIZE-1) break;
		}
		printf("returning %s.\n", outputBuffer);
		n = write(newsockfd, outputBuffer, strlen(outputBuffer));
      }
	  
	  else if (strncmp(buffer,"R6",2) == 0)   // looking for an "Robot" message
      {
        //sscanf(buffer, "R %d", &runAlgorithm);
        printf("I saw a capital R6.\n");
		int x,y;
		// send over the # of messages (blobs) to be sent
		// loop through and send each of the blob pieces of data
		x = snprintf(outputBuffer,BUFFER_SIZE-1,"%d ",24); // send the value back
		for (int i=0 ; i<3 ; ++i)
		{
			y = snprintf(outputBuffer+x,BUFFER_SIZE-1,"%d %d %d %d %d ",colorData[5].xmin[i],
						colorData[5].xmax[i],colorData[5].ymin[i],colorData[5].ymax[i],
						colorData[5].colour); // send the value back
			x = x + y; // x is the offset into the string
			// y is the amount of bytes just printed...
			if (x > BUFFER_SIZE-1) break;
		}
		printf("returning %s.\n", outputBuffer);
		n = write(newsockfd, outputBuffer, strlen(outputBuffer));
      }
	  
	  else if (strncmp(buffer,"R7",2) == 0)   // looking for an "Robot" message
      {
        //sscanf(buffer, "R %d", &runAlgorithm);
        printf("I saw a capital R7.\n");
		int x,y;
		// send over the # of messages (blobs) to be sent
		// loop through and send each of the blob pieces of data
		x = snprintf(outputBuffer,BUFFER_SIZE-1,"%d ",24); // send the value back
		for (int i=0 ; i<3 ; ++i)
		{
			y = snprintf(outputBuffer+x,BUFFER_SIZE-1,"%d %d %d %d %d ",colorData[6].xmin[i],
						colorData[6].xmax[i],colorData[6].ymin[i],colorData[6].ymax[i],
						colorData[6].colour); // send the value back
			x = x + y; // x is the offset into the string
			// y is the amount of bytes just printed...
			if (x > BUFFER_SIZE-1) break;
		}
		printf("returning %s.\n", outputBuffer);
		n = write(newsockfd, outputBuffer, strlen(outputBuffer));
      }
	  
	  else if (strncmp(buffer,"R8",2) == 0)   // looking for an "Robot" message
      {
        //sscanf(buffer, "R %d", &runAlgorithm);
        printf("I saw a capital R8.\n");
		int x,y;
		// send over the # of messages (blobs) to be sent
		// loop through and send each of the blob pieces of data
		x = snprintf(outputBuffer,BUFFER_SIZE-1,"%d ",24); // send the value back
		for (int i=0 ; i<3 ; ++i)
		{
			y = snprintf(outputBuffer+x,BUFFER_SIZE-1,"%d %d %d %d %d ",colorData[7].xmin[i],
						colorData[7].xmax[i],colorData[7].ymin[i],colorData[7].ymax[i],
						colorData[7].colour); // send the value back
			x = x + y; // x is the offset into the string
			// y is the amount of bytes just printed...
			if (x > BUFFER_SIZE-1) break;
		}
		printf("returning %s.\n", outputBuffer);
		n = write(newsockfd, outputBuffer, strlen(outputBuffer));
      }
	  
	  else if( strncmp (buffer, "Recieve Continuous", 2) == 0) // continuously send data
	  {
		printf("I saw a Recieve Continuous \n");
		int x, y;
		// send over the blob data for blobs 0 - 8
		for(int c = 0; c < 8; c++)
		{
			x = snprintf(outputBuffer, BUFFER_SIZE-1, "%d ", 24); // send the value back
			for (int i=0 ; i<3 ; ++i)
			{
				// should update BUFFER_SIZE-1 to BUFFER_SIZE-1-x!
			y = snprintf(outputBuffer+x,BUFFER_SIZE-1,"%d %d %d %d %d ",colorData[c].xmin[i],
						colorData[c].xmax[i],colorData[c].ymin[i],colorData[c].ymax[i],
						colorData[c].colour); // send the value back
			x = x + y; // x is the offset into the string
			// y is the amount of bytes just printed...
			if (x > BUFFER_SIZE-1) break;
			}
		}
	}
      
      
      else // unrecognized message from client -> sent back with "unknown message"
      {
        snprintf(outputBuffer,BUFFER_SIZE-1,"unknown message -> %s",buffer);
        n = write(newsockfd, outputBuffer, strlen(outputBuffer));
      }
      
      if (n < 0) 
      {
        printf("Error writing to socket, n = %d\n", n);
        break;
      }
      
      // clear out old data from the buffer... 
      memset(buffer, 0, n);  // there were n bytes written last time...
    }
    printf("Lost that client connection.\n");
    if (timeToQuitNow) break;  // is it time to quit?
                               // if not, we wait for another connection ...
  }
  
  printf("Server thread quitting.\n");
  pthread_exit(NULL);   // allows other threads to continue running...
}



#endif 

