#include "GETHandler.h"
#include "HTTPParameters.h"
#include "HTTPSession.h"
#include "HTTPServer.h"
#include "HTTPRequest.h"
#include "ZString.h"
#include "IMFFormData.h"
#include "Exception.h"
#include "Log.h"

namespace http {

   int GETHandler::processCommand(coreutils::ZString &request, core::TCPSession &session) {

      HTTPRequest httpRequest(request);

      HTTPSession *httpSession = static_cast<HTTPServer *>(session.server)->httpSessions.findSessionByHeader(httpRequest);

      std::stringstream content;

      HTTPParameters p(httpRequest, session, *httpSession, content, ((HTTPServer *)session.server)->actionList);

      // TODO: What should we do if we receive a request on a GET and there is a session variable?
      // If its an entry point then is it an image or link to a downloadable content that was issued
      // by the page? Referer must point to the proper entity.
      //
      // DOCUMENT: The root entry point should always be a GET request to root page.

//      entryPoints.processCommand(p);
      
      // TODO: Right here we need to do a lookup to the entry table. File requests need an entry point URL to serve.
      // TODO: Allow entry points to specify pages in the page cache or do we treat pages as automatic entry points.
      
      try {
         static_cast<HTTPServer *>(session.server)->pageList.processRequest(p);
	      httpRequest.response.setCode("200");
	      httpRequest.response.setText("OK");
      }
      catch(coreutils::Exception e) {
	      httpRequest.response.setCode("404");
	      httpRequest.response.setText("Not Found");
      }

      session.out << httpRequest.response.getResponse(content).str();

      return true;
   }

}
