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

namespace core {

   TCPServerSocket::TCPServerSocket(EPoll &ePoll, std::string url, short int port) : TCPSocket(ePoll) {
      
      struct sockaddr_in addr; 
      memset(&addr, 0, sizeof(addr));
      addr.sin_family = AF_INET;
      addr.sin_port = htons(port);
      struct hostent *hp = gethostbyname(url.c_str());
      memcpy((void *)&addr.sin_addr, hp->h_addr_list[0], hp->h_length);
      
      setDescriptor(socket(AF_INET, SOCK_STREAM, 0));
      int yes = 1;
      setsockopt(getDescriptor(), SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int));
      if(bind(getDescriptor(), (struct sockaddr *)&addr, sizeof(addr)) < 0) 
	throw Exception("Error on bind to socket");
      if(listen(getDescriptor(), 10) < 0) 
	throw Exception("Error on listen to socket");
      ePoll.registerSocket(this);      
      service = _getService();
   }

   TCPServerSocket::~TCPServerSocket() {
      close(getDescriptor());
   }
   
   void TCPServerSocket::init() {}
   
   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.address, &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);
   }

   Service * TCPServerSocket::_getService() {
      return getService();
   }
   
   Service * TCPServerSocket::getService() {
      return new Service(*this);   
   }
   
   int TCPServerSocket::processCommand(std::string command, Session *session) {      
      int sequence = 0;      
      for(auto *sessionx : service->sessions) {
	 session->out << "|" << ++sequence;
	 sessionx->output(session); 
	 session->out << "|" << std::endl;
      }
      session->send();
   }
   
}
