#include "TCPServerSocket.h"
#include "EPoll.h"
#include "Session.h"
#include "Exception.h"

namespace core {

   TCPServerSocket::TCPServerSocket(EPoll &ePoll, Service &service, IPAddress address) : TCPSocket(ePoll), service(service) {    
		service.init(this);
      setDescriptor(socket(AF_INET, SOCK_STREAM, 0));
      int yes = 1;
      setsockopt(getDescriptor(), SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int));
      if(bind(getDescriptor(), address.getPointer(), address.addressLength) < 0) 
			throw Exception("Error on bind to socket: " + std::to_string(errno));
      if(listen(getDescriptor(), 10) < 0) 
			throw Exception("Error on listen to socket");
      ePoll.registerSocket(this);      
   }

   TCPServerSocket::~TCPServerSocket() {
      close(getDescriptor());
   }
      
   void TCPServerSocket::onDataReceived(std::string data) {
      Log(LOG_DEBUG_2) << "Connection request on socket " << getDescriptor() << ".";      
      Session *session = accept();
      service.sessions.push_back(session);   
   }
   
   Session * TCPServerSocket::accept() {      
      Session *session = getSocketAccept();      
      session->setDescriptor(::accept(getDescriptor(), (struct sockaddr *)&session->ipAddress.addr, &session->ipAddress.addressLength));
      ePoll.registerSocket(session);   
      Log(LOG_DEBUG_2) << "Session started on socket " << session->getDescriptor() << ".";
      return session;
   }
   
   Session * TCPServerSocket::getSocketAccept() {
      return new Session(ePoll, service);
   }
   
   int TCPServerSocket::processCommand(std::string command, Session *session, std::stringstream &data) {      
      int sequence = 0;      
      for(auto *sessionx : service.sessions) {
         data << "|" << ++sequence;
         sessionx->output(data); 
         data << "|" << std::endl;
      }
   }
   
}
