#include "HTTPSessions.h"
#include "HTTPSession.h"
#include "Log.h"
#include <uuid/uuid.h>

namespace http {

   HTTPSession * HTTPSessions::findSessionByHeader(HTTPRequest *httpRequest) {   
      std::string sessionId = httpRequest->getHeaderKeyPairValue("Cookie", "sessionId");
      HTTPSession *session = findSessionById(sessionId, httpRequest);      
      return session;
   }

   HTTPSession * HTTPSessions::findSessionById(std::string sessionId, HTTPRequest *httpRequest) {   
      HTTPSession *httpSession;
      if(sessionId.length() > 0) {
         std::map<std::string, HTTPSession*>::iterator ix;
         ix = sessions.find(sessionId);
         httpSession = ix->second;
         if(ix == sessions.end()) {
            httpSession = createHTTPSession();
            httpRequest->response.setCookie("sessionId", httpSession->getSessionId());
         } 
         coreutils::Log(coreutils::LOG_DEBUG_1) << "http session: " << "(" << sessionId << ") " << httpSession;
         
      } else {
         httpSession = createHTTPSession();
         httpRequest->response.setCookie("sessionId", httpSession->getSessionId());
      }      
      return httpSession;
   }

   HTTPSession * HTTPSessions::createHTTPSession() {
      HTTPSession *httpSession = new HTTPSession(generateSessionId());
      sessions.insert(std::make_pair(httpSession->getSessionId(), httpSession));
      return httpSession;
   }

   std::string HTTPSessions::generateSessionId() {
      uuid_t uuid;
      uuid_generate_random(uuid);
      char uuid_s[37];
      uuid_unparse(uuid, uuid_s);
      return uuid_s;
   }
   
   int HTTPSessions::processCommand(std::string command, core::TCPSession *session, std::stringstream &data) { 
      if(sessions.size() > 0) {
         int seq = 0;
         for(auto httpSession: sessions) 
           data << "|" << ++seq << "|" << httpSession.second->getSessionId() << "|" << std::endl;
         
      }
      else 
        data << "There are no sessions active." << std::endl;         
      return 1;
   }
   
}
