#include "UDPServerSocket.h"
#include "EPoll.h"
#include "TCPSession.h"

namespace core {
   
   UDPServerSocket::UDPServerSocket(EPoll &ePoll, std::string url, short int port, std::string commandName) : UDPSocket(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));
      
      bind(getDescriptor(), (struct sockaddr *)&addr, sizeof(addr));
      
      listen(getDescriptor(), 10);
      
//      ePoll.registerSocket(this);
      
   }
   
   UDPServerSocket::~UDPServerSocket() {
      close(getDescriptor());
   }
   
   void UDPServerSocket::onDataReceived(std::string data) {
      
      // TODO: Here we read the client address and establish a session object or
      // or find it in the vector if it was already in use and then
      // send the data to the session. 
      // 
      //   sessions.push_back(session);
      // 
      //   BMASession::onDataReceived(data, length);
      // 
   }
   
   int UDPServerSocket::processCommand(std::string request, std::stringstream &data) {
      
      int sequence = 0;
      
//      for(auto *session : sessions) {
//         data << "|" << ++sequence;
//         session->output(data); 
//         data << "|" << std::endl;
//      }

      return 1;
   }
   
}
