/*! @file

    @id $Id$
*/
//       1         2         3         4         5         6         7         8
// 45678901234567890123456789012345678901234567890123456789012345678901234567890

#ifndef __TEMPORARYFILE_HXX__
#define __TEMPORARYFILE_HXX__

#include <QtCore/QTemporaryFile>
#include <QtCore/QRegExp>

#include <QtCore/QDebug>

class TemporaryFile: public QFile {
    Q_OBJECT;
    
  public:
    
    TemporaryFile(QString filename): _autoRemove(false) {
      if (exists(filename)) {
        QString prefix(filename);
        QString suffix(filename);
        prefix.remove(QRegExp("\\.[^.]*$"));
        suffix.remove(QRegExp("^.*\\."));
        qDebug()<<"filename"<<filename
                <<"prefix"<<prefix
                <<"suffix"<<suffix;
        if (prefix==suffix) suffix.clear();
        for (unsigned long i(0); i<10000; ++i)
          if (!exists(filename =
                      QString("%1_%2.%3")
                      .arg(prefix)
                      .arg(i, 4, 10, QChar('0'))
                      .arg(suffix))) break;
      }
      qDebug()<<"filename"<<filename;
      setFileName(filename);
    }

    bool open() {
      return QFile::open(QIODevice::ReadWrite);
    }

    void setAutoRemove(bool flag) {
      _autoRemove = flag;
    }

    ~TemporaryFile() {
      qDebug()<<"_autoRemove"<<_autoRemove
              <<"exists()"<<exists();
      if (_autoRemove && exists()) {
        qDebug()<<"Remove: "<<fileName();
        remove();
      } else {
        qDebug()<<"Don't remove: "<<fileName();
      }
    }

  private:

    bool _autoRemove;
};

#endif
