#include <iostream>
#include <cstdlib>
#include "tcp_stream.h"

using namespace std;
using namespace net_tools;

WSADATA stWSAData;  // WinSock DLL Info.

#define WSA_MAJOR_VERSION 1
#define WSA_MINOR_VERSION 1
#define WSA_VERSION MAKEWORD(WSA_MAJOR_VERSION, WSA_MINOR_VERSION)

int
main()
{
   WSAStartup(WSA_VERSION, &stWSAData);

   //cout << "Content-type: text/html\r\n\r\n" << flush;

   tcp_stream client("127.0.0.1", 1995);

   if(client) {
      if(strcmp(getenv("REQUEST_METHOD"), "GET") == 0) {
         client << getenv("QUERY_STRING") << "\n";
      }
      else {
         int size = atoi(getenv("CONTENT_LENGTH"));
         if(size > 0) {
            char * buffer = new char [size+1];

            memset(buffer, 0, size+1);

            cin.read(buffer, size);

            client << buffer << "\n";

            delete [] buffer;
         }
      }

      char ch;

      ch = client.get();
      string temp;
      while(client) {
         //cout << ch << flush;
         temp += ch;

         ch = client.get();
      }

      cout << temp << flush;

      client.close();
   }
   else {
      cout << "Content-type: text/html\r\n\r\n" << flush;
      cout << "<HTML>" << endl;
      cout << "<HEAD>" << endl;
      cout << "<TITLE>Error #101: Service unavailable..</TITLE>" << endl;
      cout << "</HEAD>" << endl;
      cout << "<BODY BGCOLOR=\"WHITE\">" << endl;
      cout << "CGId Version: 1.0.0<BR><BR>" << endl;
      cout << "<H1>Error #101: Service unavailable...</H1>" << endl;
      cout << "</BODY>" << endl;
      cout << "</HTML>" << endl << flush;
   }

   return 0;
}
