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

namespace core {

   TCPServer::TCPServer(EPoll &ePoll, IPAddress address) : TCPSocket(ePoll) {    
      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 coreutils::Exception("Error on bind to socket: " + std::to_string(errno));
      if(listen(getDescriptor(), 10) < 0) 
	throw coreutils::Exception("Error on listen to socket");
   }
   
   TCPServer::~TCPServer() {
      close(getDescriptor());
   }
   
   void TCPServer::onDataReceived(std::string data) {
      TCPSession *session = accept();
      if(session) sessions.push_back(session);   
   }
   
   TCPSession * TCPServer::accept() {      
      TCPSession *session = getSocketAccept(ePoll);      
      session->setDescriptor(::accept(getDescriptor(), (struct sockaddr *)&session->ipAddress.addr, &session->ipAddress.addressLength));
      
      //      if(blackList && blackList->contains(session->ipAddress.getClientAddress())) {
      //         session->shutdown();
      //         Log(LOG_WARN) << "Client at IP address " << session->ipAddress.getClientAddress() << " is blacklisted and was denied a connection.";
      //         return NULL;
      //      }
      //
      //      if(whiteList && !whiteList->contains(session->ipAddress.getClientAddress())) {
      //         session->shutdown();
      //         Log(LOG_WARN) << "Client at IP address " << session->ipAddress.getClientAddress() << " is not authorized and was denied a connection.";
      //         return NULL;
      //      }
      // 
      coreutils::Log(coreutils::LOG_DEBUG_2) << "Session started on socket " << session->getDescriptor() << ".";
      return session;
   }
   
   void TCPServer::removeFromSessionList(TCPSession *session) {      
      std::vector<TCPSession *>::iterator cursor;
      for(cursor = sessions.begin(); cursor < sessions.end(); ++cursor)
        if(*cursor == session)
          sessions.erase(cursor);
   }
   
   void TCPServer::sessionErrorHandler(std::string errorString) {   	
      throw coreutils::Exception(errorString);
   }   
   
   TCPSession * TCPServer::getSocketAccept(EPoll &ePoll) {
      return new TCPSession(ePoll, *this);
   }
   
   void TCPServer::output(TCPSession *session) {      
      session->out << "|" << session->ipAddress.getClientAddressAndPort();       
   }
   
   int TCPServer::processCommand(std::string command, TCPSession *session, std::stringstream &data) {      
      int sequence = 0;      
      for(auto *sessionx : sessions) {
         data << "|" << ++sequence;
         sessionx->output(data); 
         data << "|" << std::endl;
      }
   }
   
}
