#include <iostream>
#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();
      while(client) {
         cout << ch << flush;

         ch = client.get();
      }

      client.close();
   }
   else {
      cout << "Content-type: text/html\r\n\r\n" << flush;
      cout << "<H1>Error #101: Service unavailable...</H1>" << endl << flush;
   }

   cout << "<BR><BR>" << endl << flush;
   cout << "GET:<BR>" << endl << flush;
   cout << "<FORM METHOD=GET ACTION=/scripts/gateway.exe>" << endl 
        << "<INPUT TYPE=HIDDEN NAME=cgilet VALUE=hello>" << endl
        << "Name: <INPUT TYPE=TEXT NAME=name><BR><INPUT TYPE=SUBMIT><BR>" << endl
        << "</FORM>" << endl << endl << flush;

   cout << "POST:<BR>" << endl << flush;
   cout << "<FORM METHOD=POST ACTION=/scripts/gateway.exe>" << endl
        << "<INPUT TYPE=HIDDEN NAME=cgilet VALUE=hello>" << endl
        << "Name: <INPUT TYPE=TEXT NAME=name><BR><INPUT TYPE=SUBMIT><BR>" << endl
        << "</FORM>" << endl << endl << flush;

   /*
   cout << "PERSON:<BR>" << endl << flush;
   cout << "<FORM METHOD=POST ACTION=/cgi-bin/test.cgi>" << endl
        << "<INPUT TYPE=HIDDEN NAME=cgilet VALUE=person>" << endl
        << "<INPUT TYPE=SUBMIT><BR>" << endl
        << "</FORM>" << endl << endl << flush;
   */

   return 0;
}
