#include "Session.h"
#include "Log.h"
#include "TCPServerSocket.h"

namespace core {

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