#include "server.h"
#include <libgen.h> // basename

/*  Server waits for an incoming client connection, accepts the connection,
 *  checks if the client sent anything, if not, waits 50ms, and checks again.
 *  If there is no data the client is sent "timeout" and is closed.
 *  Otherwise whatever data is stored, responded to, and client is closed.
 *  
 *  Normally the client handling would be less clunky but Msft does not support
 *  the fork() routine so we are going to accept the limitations that are
 *  imposed by this clunkiness.  Mostly: clients are limited to 50ms to transmit
 *  their data and that the worst case throughput is reduced to 20 connects per
 *  second rather than the full throughput of the network card (>10,000,000/s)
 */
int main(int argc, char *argv[]) {
    int sock;

    fprintf(stderr, "%s - testing tcp socket\n", basename(argv[0]));

    #ifdef _WIN32
    // if compiling on Msft include the winsock librariy (ws2_32.lib)
    WSADATA wsaData;
    if(msftVendorLockInCode(&wsaData)) return 1;
    #endif

    // terminate if we cannot get a socket that can be used to accept clients
    if(!(sock = setup())) return 1;

    while(1) {
        /*  be a server for a second, up to one client can be handled per call
         *  if a client is accepted right at the one second mark, technically
         *  this call could take one second and ten milliseconds to return, but
         *  whatever
         *
         *  terminate if socket becomes unusable (see: acceptOkay)
         */

        // demo: alternate between alwaysBad, alwaysGood, alwaysNotEnough
        if(!faceItMetal(sock, 1000 /* ms */, alwaysBad)) return softCuteBunnies(1);
        if(!faceItMetal(sock, 1000 /* ms */, alwaysGood)) return softCuteBunnies(1);
        if(!faceItMetal(sock, 1000 /* ms */, alwaysNotEnough)) return softCuteBunnies(1);
    }

    return softCuteBunnies(0);
}
