#include "TCPClient.h"

#define DEBUG_CL

TCPClient::TCPClient(WiFiClient client, uint8_t id, uint16_t dataBufferSize) : _client(client), 
_clientState(NEW),
_error(OK),
_data(NULL), 
_dataSize(0),
_dataBufferSize(dataBufferSize+1),
_newDataAvailable(false),
_id(id)
{
  #ifdef DEBUG_CL
  Serial.println("TCPClient : Standard constructor called");
  #endif
  
	uint8_t *p = (uint8_t *) malloc(sizeof(uint8_t) * _dataBufferSize);
	if(p != NULL)
		_data = p;
	else
		_error = MALLOC_ERR;
}

TCPClient::TCPClient(const TCPClient &Object) : _client(Object._client),
_clientState(Object._clientState),
_error(Object._error),
_data(NULL), 
_dataSize(Object._dataSize),
_dataBufferSize(Object._dataBufferSize),
_newDataAvailable(Object._newDataAvailable),
_id(Object._id)
{
  #ifdef DEBUG_CL
  Serial.println("TCPClient : Copy constructor called");
  #endif
  
  uint8_t *p = (uint8_t *) malloc(sizeof(uint8_t) * _dataBufferSize);
  if(p != NULL)
  {
    _data = p;
    memcpy(_data,Object._data,_dataSize);
  }
  else
    _error = MALLOC_ERR;
}

TCPClient::~TCPClient()
{
  #ifdef DEBUG_CL
  Serial.println("TCPClient : Destructor called");
  #endif
  
	free(_data);
}

bool TCPClient::operator==(TCPClient& Object)
{
	return this->_client == Object._client;
}

bool TCPClient::closeConnection()
{
  _client.stop();
}

void TCPClient::freeDataBuffer(uint16_t size)
{
  if(size > _dataBufferSize-1) size = _dataBufferSize - 1;

  uint16_t secureSize = size > _dataSize ? _dataSize : size;
  
  if(*(_data + secureSize) == '\0')
  {
    #ifdef DEBUG_CL
    Serial.println("Its the terminating string");
    #endif
  }
  
  strcpy((char *)_data, (char *)_data + secureSize);
  _dataSize -= secureSize;
}
