/***************************************************************************
**
**  This file is part of QGpCoreTools.
**
**  This library is free software; you can redistribute it and/or
**  modify it under the terms of the GNU Lesser General Public
**  License as published by the Free Software Foundation; either
**  version 2.1 of the License, or (at your option) any later version.
**
**  This file is distributed in the hope that it will be useful, but WITHOUT
**  ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
**  FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
**  License for more details.
**
**  You should have received a copy of the GNU Lesser General Public
**  License along with this library; if not, write to the Free Software
**  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
**
**  See http://www.geopsy.org for more information.
**
**  Created: 2006-11-10
**  Copyright: 2006-2019
**    Marc Wathelet
**    Marc Wathelet (LGIT, Grenoble, France)
**
***************************************************************************/

#ifndef TAR_H
#define TAR_H

#include <zlib.h>

#include "QGpCoreToolsDLLExport.h"
#include "Translations.h"
#include "CoreApplication.h"
#include "Trace.h"

namespace QGpCoreTools {

struct TarHeader;

class QGPCORETOOLS_EXPORT Tar
{
  TRANSLATIONS("Tar")
public:
  Tar();
  ~Tar();

  bool open(QString file, QIODevice::OpenMode m);
  void close();
  QString fileName() const {return _fileName;}

  bool addFile(QString fileName, const QByteArray& data);
  bool nextFile(QString& fileName, QByteArray& data, bool cache=false  );
  bool file(const QString fileName, QByteArray& data);
  bool rewind();
private:
  inline bool writeBlock(const char * buffer);
  inline bool readBlock(char * buffer);
  char * int2octal(qint64 val);
  qint64 octal2int(const char * octStr);
  uint checksum(TarHeader& fh);
  bool readFile(TarHeader& fh, QByteArray& data);

  gzFile _f;
  QString _fileName;
  QIODevice::OpenMode _mode;
  QCache<QString, QByteArray> _cachedFiles;
  QMap<QString, z_off_t> _fileOffsets;
};

inline bool Tar::writeBlock(const char * buffer)
{
  TRACE;
  // To ensure compatibility with old zlib releases (void *) is requested.
  if(gzwrite (_f, (void *) buffer, 512)!=512) {
    App::log(tr("Cannot write block in tar file\n") );
    return false;
  } else {
    return true;
  }
}

inline bool Tar::readBlock(char * buffer)
{
  TRACE;
  int nb=gzread (_f, buffer, 512);
  if(nb!=512) {
    App::log(1, tr("Cannot read a block of 512 bytes in tar file\n"));
    return false;
  } else {
    return true;
  }
}

} // namespace QGpCoreTools

#endif // TAR_H
