/**
 * File: time-server-sequential.cc
 * ----------------------------
 * This is a server program that sequentially handles incoming requests and sends 
 * back a single string containing the current date/time to the client.
 */

#include <iostream>                // for cout, cett, endl
#include <ctime>                   // for time, gmtime, strftim
#include <sys/socket.h>            // for socket, bind, accept, listen, etc.
#include <unistd.h>                // for close
#include "server-socket.hh"

using namespace std;


// This function returns a string representation of the current date and time.
static string getCurrentDateTime() {
  time_t rawtime;
  time(&rawtime);
  struct tm tm;
  gmtime_r(&rawtime, &tm);
  char timestr[128]; // more than big enough
  /* size_t len = */ strftime(timestr, sizeof(timestr), "%c", &tm);
  return timestr;
}

int main(int argc, char *argv[]) {
  if (argc < 2) {
    cerr << "Error: please specify a port number to run." << endl;
    return 1;
  }
  
  // Create a server socket we can use to listen for incoming requests
  unsigned short port = atoi(argv[1]);
  int serverSocket = createServerSocket(port);
  
  cout << "Server listening on port " << port << "." << endl;
  while (true) {
    // Wait for an incoming client connection and establish a descriptor for it
    int clientDescriptor = accept(serverSocket, NULL, NULL);

    cout << "Got incoming request!" << endl;

    // Make a string of the current date and time and send it to the client
    string dateTime = getCurrentDateTime();

    // we'll assume here that it writes all bytes successfully
    write(clientDescriptor, dateTime.c_str(), dateTime.length());
    close(clientDescriptor);
  }

  close(serverSocket);

  return 0;
}
