// fgpickregexp.cc

#include "fgpickregexp.h"

// Dir listings
#ifndef _FGDLIST_H
#include "fgdlist.h"
#endif

// Action lists
#ifndef _FGALIST_H
#include "fgalist.h"
#endif

// The download file action
#ifndef _FGDLACTION_H
#include "fgdlaction.h"
#endif

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

#include <regex.h>

FGPickRegexp::FGPickRegexp(FGConnectionInterface* pConnIf,
                           const FGString& regexp)
: FGFilePickerInterface(pConnIf), mpRegExp(0)
{
  mpRegExp = new regex_t;

  try {
    int ret = regcomp(mpRegExp, regexp, REG_EXTENDED | REG_NOSUB);
    if (ret != 0) {
      throw FGException(FGException::kInvalidRegexp);
    }
  }
  catch (FGException&) {
    delete mpRegExp;
    throw;
  }
}

FGPickRegexp::~FGPickRegexp()
{
  if (mpRegExp != 0) {
    regfree(mpRegExp);
    delete mpRegExp;
  }
}


FGActionList
FGPickRegexp::DecideActions(const FGDirListing& localDir,
                            const FGDirListing& remoteDir)
{
  // The picker for the "normal" operation (non recursive),
  // leaves all local files intact
  // Very simple rule: grab any file in the remoteDir that is
  // not in the localDir and matches regexp
  FGActionList ret;

  // Get list of files in remote but not local
  FGDirListing newFiles = FGDirListing::GetRHSOnlyFiles(localDir, remoteDir);

  // Pare down listing to only regexp matches
  FGDirListing finalList("NOTUSED");
  std::vector<FGFileInfo>::const_iterator iFiles;
  for (iFiles = newFiles.begin(); iFiles != newFiles.end(); iFiles++) {
    int match = regexec(mpRegExp, iFiles->GetFileName(), 0, 0, 0);
    if (match == 0) {
      finalList.push_back(*iFiles);
    }
  }

  // Make a "download" action for all the above files
  for (iFiles = finalList.begin(); iFiles != finalList.end(); iFiles++) {
    FGActionInterface* pNewAction;

    pNewAction = new FGDownloadAction(iFiles->GetFileName(), mpConnIf,
                                      localDir.GetDirName(),
                                      iFiles->GetSize());
    ret.push_back(pNewAction);
  }

  return ret;
}
