#include "cclient.h"

using namespace std;

cclient::cclient(char* ip,unsigned short port)
{
   /* connect to server */
   sockaddr_in server_info;
   server_info.sin_family=AF_INET;
   server_info.sin_port=htons(port);
   server_info.sin_addr.s_addr=inet_addr(ip);
   connection=connect(s,(sockaddr*) &server_info,sizeof(server_info))==0;
   /* connect to server */
}

bool cclient::connected()
{
   return connection;
}

void cclient::write_packet(int n,char* packet)
{
   /* append packet to sendbuffer */
   char header[2]={strlen(packet),0};
   sb.append(header);
   sb.append(packet);
   /* append packet to sendbuffer */
}

void cclient::update()
{
   /* clear FD_SET */
   FD_ZERO(&read_sockets);
   FD_ZERO(&write_sockets);
   /* clear FD_SET */

   /* add socket to FD_SET */
   FD_SET(s,&read_sockets);
   FD_SET(s,&write_sockets);
   /* add socket to FD_SET */

   /* read and write data */
   if (select(s+1,&read_sockets,&write_sockets,0,&delay)>0)
   {
      /* read data and disconnect */
      if (FD_ISSET(s,&read_sockets))
      {
         char buffer[1025];
         int bytes=recv(s,buffer,1024,0);
         if (bytes>0)
         {
            buffer[bytes]=0;
            rb.append(buffer);
         }
         else
         {
            closesocket(s);
            connection=0;
         }
      }
      /* read data and disconnect */

      /* send data and remove it from the sendbuffer */
      if (FD_ISSET(s,&write_sockets))
      {
         int bytes=send(s,sb.data(),sb.size(),0);
         sb.erase(0,bytes);
      }
      /* send data and remove it from the sendbuffer */
   }
   /* read and write data */
}

int cclient::read_packet(char* packet)
{
   /* packet flag */
   int n=0;
   /* packet flag */

   /* copy and remove packet from receivebuffer */
   if (rb.size()>1)
   {
      int length=rb[0];
      if (rb.size()>length)
      {
         rb.copy(packet,length,1);
         packet[length]=0;
         rb.erase(0,length+1);
         n=1;
      }
   }
   /* copy and remove packet from receivebuffer */

   /* return packet flag */
   return n;
   /* return packet flag */
}
