// fgdlaction.cc

#include "fgdlaction.h"

// Downloading involves interfacing with remote connection
#ifndef _FGCONI_H
#include "fgconi.h"
#endif

#ifndef _FGFSHELP_H
#include "fgfshelp.h"
#endif

#ifndef _FGSTRING_H
#include "fgstring.h"
#endif

#ifndef _FGEXC_H
#include "fgexc.h"
#endif

#ifndef _FGLOGGER_H
#include "fglogger.h"
#endif

FGDownloadAction::FGDownloadAction(const FGString& fname,
                                   FGConnectionInterface* pConnIf,
                                   const FGString& localDir,
                                   int size)
: mpConnIf(pConnIf), mFileName(fname), mLocalDir(localDir),
  mDestFD(-1), mFileSize(size)
{
}

FGDownloadAction::~FGDownloadAction()
{
}

void
FGDownloadAction::VirtualDo(void) const
{
  FGString msg;
  msg = "Starting download of file `";
  msg += mFileName;
  msg += '\'';
  FGLogger::GetLogger().LogMsg(msg, FGLogger::kFGLLVerbose);

  // Interface already has directory state ready for direct grab
  // Also, we're connected at this point
  int dataFD = mpConnIf->GetFile(mFileName);

  // Create the destination file for writing
  FGString destName(mLocalDir);
  destName += '/';
  destName += mFileName;

  try {
    int destFD = FGFileSystemHelper::CreateLocalFile(destName);
    FGFileSystemHelper::TransferRemoteToLocal(dataFD, destFD, mFileSize);
  }
  catch (FGException& e) {
    mpConnIf->PostFileTransfer();
    throw e;
  }

  // Success - cool better log message
  msg = "Successful transfer of file `";
  msg += mFileName;
  msg += '\'';
  FGLogger::GetLogger().LogMsg(msg, FGLogger::kFGLLInfo);

  mpConnIf->PostFileTransfer();
}

void
FGDownloadAction::Abort(void) const
{
  // Something has gone wrong during the download
  // Delete the file we started to download
  // Ignore errors in case we didn't get as far as creating the file
  FGString delFile(mLocalDir);
  delFile += '/';
  delFile += mFileName;

  try {
    FGFileSystemHelper::DeleteFile(delFile);
  }
  catch (FGException&) {
    // Do nothing
  }
}
