#include "Session.h"
#include "Log.h"
#include "Service.h"

namespace core {

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