#include "FTPClient.h"

FTPClient::FTPClient(WiFiClient client, uint8_t id, uint16_t clientCommandDataBufferSize) : TCPClient(client, id, clientCommandDataBufferSize),
_ftpCommand({'\0'}),
_cmdParameters(NULL),
_loggedIn(false),
_username(NULL),
_currentDirectory(NULL),
_waitingForDataConnection(false),
_ftpClientState(FTPServer<FTPClient>::FTPClientState::WAITING_FOR_COMMANDS),
_binaryFlag(FTPServer<FTPClient>::BinaryFlag::OFF),
_dataTransferPending(FTPServer<FTPClient>::FTPClientDataTransfer::NONE)
{
  
}

FTPClient::~FTPClient()
{
	delete _cmdParameters;
  free(_username);
  free(_currentDirectory);
}

void FTPClient::setDataClient(WiFiClient dataClient)
{
  _dataClient = dataClient;
}

boolean FTPClient::parseCommandAndParameters()
{
  //We remove the cr lf at the end
  char *cr = strchr((char *)_data,'\r'); *cr = '\0';
  char *cmdDelimiter = strchr((char *)_data,' ');

  if(cmdDelimiter == NULL) //It means that we do not have any parameters
  {
    cmdDelimiter = (char *)_data + strlen((char *)_data) - 1;
    strcpy(_ftpCommand, (char *)_data);
  }
  else //we do
  {
    strncpy(_ftpCommand, (char *)_data, cmdDelimiter - (char *)_data);
    _ftpCommand[cmdDelimiter - (char *)_data] = '\0'; // /!\ strncpy does not append the terminating string character
  }

  //We get the parameters : 
  DictionaryHelper::StringEntity params(cmdDelimiter+1); //+1 to skip the first space
  delete _cmdParameters;
  _cmdParameters = params.split(' ');
  
  //At the end, we flush the buffer:
  freeDataBuffer(_dataSize);
}

void FTPClient::setUsername(const char *username)
{
  if(username != NULL)
  {
    _username = (char *) malloc((sizeof(char) * strlen(username)) + 1);
    strcpy(_username, username);
  }
}
