/* ****************************************************************************
  This file is part of KBabel

  Copyright (C) 2002 by Marco Wegner <mail@marcowegner.de>

  This program is free software; you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation; either version 2 of the License, or
  (at your option) any later version.

  This program 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 General Public License for more details.

  You should have received a copy of the GNU General Public License
  along with this program; if not, write to the Free Software
  Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.

**************************************************************************** */


#include <qdir.h>
#include <qfile.h>
#include <qfileinfo.h>
#include <qstring.h>
#include <qstringlist.h>

#include <kapplication.h>
#include <kconfig.h>
#include <kio/netaccess.h>
#include <klineeditdlg.h>
#include <klocale.h>
#include <kmessagebox.h>
#include <kstandarddirs.h>
#include <ktar.h>
#include <kurl.h>

#include "catalogsettings.h"
#include "kbmailer.h"

KBabelMailer::KBabelMailer()
{
  tempDir = locateLocal("tmp", QString::null);
  readConfig();
}

KBabelMailer::~KBabelMailer()
{
  // clean up before leaving
  removeTempFiles();
  delete config;
}

void KBabelMailer::sendOneFile(const QString& fileName)
{
  if (!singleFileCompression) {
    kapp->invokeMailer("", "", "", "", "", "", fileName);
  } else {
    QFileInfo info(fileName);
    QString archive = createArchive(QStringList(fileName), info.baseName());
    if (!archive.isNull()) {
      kapp->invokeMailer("", "", "", "", "", "", archive);
    }
  }
}

void KBabelMailer::sendFiles(QStringList fileList, const QString& initialName)
{
  QString archive = createArchive(fileList, initialName);
  if (!archive.isNull()) {
    kapp->invokeMailer("", "", "", "", "", "", archive);
  }
}

QString KBabelMailer::createArchive(QStringList fileList, QString initialName)
{
  // do nothing if there are no files in the list
  if (fileList.empty())
    return QString::null;

  // determine the name of the archive, do nothing if none is given
  // or Cancel was pressed
  bool result = false;
  if (initialName.isNull())
    initialName = "translations";
  QString archiveName = KLineEditDlg::getText(i18n("Enter the name of the "
    "archive without file extension"), initialName, &result, 0);
  if (!result || archiveName.isEmpty())
    return QString::null;

  // file extensions are determined from the type of compression
  if (archiveName.endsWith(".tar.bz2")) {
    archiveName.truncate(archiveName.find(".tar.bz2"));
  } else if (archiveName.endsWith(".tar.gz")) {
    archiveName.truncate(archiveName.find(".tar.gz"));
  }

  // set the correct extension and mimetype
  QString extension, mimetype;
  if (bzipCompression) {
    extension = ".tar.bz2";
    mimetype = "application/x-bzip2";
  } else {
    extension = ".tar.gz";
    mimetype = "application/x-gzip";
  }
  KTar archive(tempDir + archiveName + extension, mimetype);

  if (!archive.open(IO_WriteOnly)) {
    KMessageBox::error(0, i18n("Error while trying to create archive file."));
    return QString::null;
  } else {
    QStringList::Iterator it;
    for (it = fileList.begin(); it != fileList.end(); ++it) {
      KURL url(*it);
      QString poTempName;
      if (!KIO::NetAccess::download(url, poTempName)) {
        KMessageBox::error(0, i18n("Error while trying "
          "to read file %1.").arg(url.prettyURL()));
      } else {
        QFile poFile(poTempName);
        if (!poFile.open(IO_ReadOnly)) {
          KMessageBox::error(0, i18n("Error while trying "
            "to open file %1.").arg(poTempName));
        } else {
          QFileInfo info(poFile.name());
          archive.writeFile(info.fileName(), "user", "group",
            poFile.size(), poFile.readAll());
          poFile.close();
        }
        KIO::NetAccess::removeTempFile(poTempName);
      }
    }
    archive.close();
  }

  // add archive's filename to the list of files to be deleted later
  tempFileNames << archive.fileName();
  return archive.fileName();
}

void KBabelMailer::readConfig()
{
  config = new KConfig("kbabelrc");
  KConfigGroupSaver cs(config, "Misc");
  bzipCompression = config->readBoolEntry("BZipCompression",
    Defaults::Misc::useBzip);
  singleFileCompression = config->readBoolEntry("CompressSingleFile",
    Defaults::Misc::compressSingleFile);
}

void KBabelMailer::removeTempFiles()
{
  if (tempFileNames.empty())
    return;

  QDir d(tempDir);
  QStringList::Iterator it;
  for (it = tempFileNames.begin(); it != tempFileNames.end(); ++it)
    d.remove(*it);
}
