#include "TCPSession.h"
#include "TCPServer.h"
#include "Log.h"

namespace core {

   TCPSession::TCPSession(EPoll &ePoll, TCPServer &server) : TCPSocket(ePoll), server(server) {}
   
   TCPSession::~TCPSession() {
      server.removeFromSessionList(this);
   }
      
   void TCPSession::output(std::stringstream &data) {
      data << "|" << ipAddress.getClientAddressAndPort();
   }
   
   void TCPSession::protocol(std::string data = "") {
      if(data.length() > 0) {
         if(!server.commands.processRequest(data, this, out)) 
           server.sessionErrorHandler("Invalid data received.");
         send();
      }
   }
   
   void TCPSession::onRegister() {
      protocol();
   }
   
   void TCPSession::onDataReceived(std::string data) {
      protocol(data);
   }
   
   void TCPSession::sendToAll() {
      for(auto session : server.sessions) { 
         if(session != this)
            session->write(out.str());
         }
      out.str("");
   }
   
   void TCPSession::sendToAll(SessionFilter filter) {
      for(auto session : server.sessions) { 
         if(filter.test(*session)) {
            if(session != this)
              session->write(out.str());
         }
      }
      out.str("");
   }
   
   void TCPSession::send() {
      write(out.str());
      out.str("");
   }
   
}
