/// BasicVolumeFormat.cpp
/** Responsible for writing target output files.
*/

#include <iostream>
#include <algorithm>
#include <string>
#include <vector>

#include <wx/string.h>

#include "BasicVolumeFormat.h"

using namespace jcs;

///
/**
*/
BasicVolumeFormat::BasicVolumeFormat(const char* filename, 
const char* header_extension,
const char* raw_extension) 
: mFileName(filename),
mHeaderExtension(header_extension),
mRawExtension(raw_extension)
{
  wxFileName::Mkdir(mFileName.GetPath(wxPATH_GET_VOLUME), 0777, wxPATH_MKDIR_FULL);
}

///
/**
*/
BasicVolumeFormat::~BasicVolumeFormat()
{
  if (mHeaderFile.is_open()) {
    mCloseHeaderFile();
  }
  if (mRawDataFile.is_open()) {
    mCloseRawDataFile();
  }
}


/// Tries to open a header file in given 'mode'.
/**
  \param mode Open mode for file.
  \return Status code, false on bad file name, false on failure of 'open' call,
  true on success of 'open' call.
*/
int
BasicVolumeFormat::mOpenHeaderFile(std::ios::openmode mode) 
{
  bool retval = false;

  if (mFileName.IsOk()) {
    if (mHeaderFile.is_open()) {
      mHeaderFile.close();
    }
    mHeaderFile.clear();
    mFileName.SetExt(mHeaderExtension);
    
    // Test possible overwrite condition.
    if (mFileName.FileExists()) {
      std::string errorMsg = "Warning: File exists, will overwrite ";
      errorMsg += mFileName.GetFullPath();
      wxLogError(wxFormatString(errorMsg));
      std::cout << errorMsg << std::endl;
    }

    mHeaderFile.open((const char *) mFileName.GetFullPath(), mode);
    retval = mHeaderFile.good();
  }
  return retval;
}


/// Writes 'n_bytes' of 'data'.
/** Overwrites a non-open file, appends to an open file.
    \param data Pointer to data to be written.
    \param n_bytes Number of bytes to write.
    \return Status code, false on file failure, true on success.
*/
int
BasicVolumeFormat::AppendRawData(char* data, size_t n_bytes)
{
  int retval = false;
  wxString extUsed;
  std::ios_base::openmode o_mode = std::ios::out | std::ios::binary;
  
  if (mRawExtension != _T("")) {
    extUsed = mRawExtension;
    o_mode |= std::ios::trunc;
  }
  else {
    extUsed = mHeaderExtension;
    o_mode |= std::ios::app;
  }
  mFileName.SetExt(extUsed);

  if (mFileName.IsOk()) {
    if (!mRawDataFile.is_open()) {
      if (mRawExtension != _T("")) {
        mRawDataFile.clear();
      }
      
      // Test possible overwrite condition.      
      if (mFileName.FileExists() && (o_mode & std::ios::trunc)) {
        std::string errorMsg = "Warning: File exists, will overwrite ";
        errorMsg += mFileName.GetFullPath();
        wxLogError(wxFormatString(errorMsg));
        std::cout << errorMsg << std::endl;
      }
      mRawDataFile.open((const char *) mFileName.GetFullPath(), o_mode);
    }

    if (mRawDataFile.good()) {
      mRawDataFile.write(data, n_bytes);
      retval = true;
    }
  }
  return retval;
}
