#include "HTTPHandler.h"
#include "HTTPSession.h"
#include "HTTPServer.h"
#include "HTTPRequest.h"
#include "PString.h"
#include "IMFFormData.h"
#include "Log.h"

namespace http {
      
   int HTTPHandler::processCommand(std::string request, core::TCPSession *session, std::stringstream &data) {

      coreutils::Log(coreutils::LOG_DEBUG_1) << "DATA[" << request << "]";
      coreutils::PString request1(request);

      switch(mode) {	   
       case REQUEST:	         
	coreutils::Log(coreutils::LOG_DEBUG_2) << "Processing request data... '" << request1.str() << "'";

        httpRequest = new HTTPRequest(request1);
	
        session->server.commands.grabInput(session, *this);
        mode = IMF;
       
       case IMF:
        httpRequest->parse(request1);	 
        if(request == "") {	      
	    session->server.commands.clearGrab(session);	
	    mode = REQUEST;	 			   
	    processHTTPRequest(session, data);
	 }
      }            

      return true;
   }      

   bool HTTPHandler::processHTTPRequest(core::TCPSession *session, std::stringstream &data) {
   
      HTTPSession *httpSession = static_cast<HTTPServer&>(session->server).httpSessions.findSessionByHeader(httpRequest);
      
      std::stringstream content;
      
      if(static_cast<HTTPServer &>(session->server).pageList.processRequest(httpRequest, session, httpSession, content)) {
	 std::string contentType = httpRequest->getHeader("Content-Type");
	 if(contentType == "multipart/form-data") {
	    coreutils::IMFFormData *formdata = (coreutils::IMFFormData *)httpRequest->getBody();
	    coreutils::Log(coreutils::LOG_DEBUG_2) << "username is '" << formdata->getByName("username") << "'";				
	 }
	 
	 httpRequest->response.setCode("200");
	 httpRequest->response.setText("OK");
	 data << httpRequest->response.getResponse(content.str());
      } 
      
      else {
	 httpRequest->response.setCode("404");
	 httpRequest->response.setText("Not Found");
	 data << httpRequest->response.getResponse(content.str());
      }
      return true;
   }
   
}
