/*
 * ark -- archiver for the KDE project
 *
 * Copyright (C) 2008 Harald Hvaal <haraldhv@stud.ntnu.no>
 * Copyright (C) 2009 Raphael Kubo da Costa <kubito@gmail.com>
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES ( INCLUDING, BUT
 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION ) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * ( INCLUDING NEGLIGENCE OR OTHERWISE ) ARISING IN ANY WAY OUT OF THE USE OF
 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "addtoarchive.h"
#include "adddialog.h"
#include "archive.h"
#include "jobs.h"

#include <KConfig>
#include <kdebug.h>
#include <kjobtrackerinterface.h>
#include <kmessagebox.h>
#include <klocale.h>
#include <KStandardDirs>

#include <QFileInfo>
#include <QDir>
#include <QPointer>
#include <QTimer>

namespace Kerfuffle
{
AddToArchive::AddToArchive(QObject *parent)
        : KJob(parent), m_changeToFirstPath(false)
{
}

AddToArchive::~AddToArchive()
{
}

void AddToArchive::setAutoFilenameSuffix(const QString& suffix)
{
    m_autoFilenameSuffix = suffix;
}

void AddToArchive::setChangeToFirstPath(bool value)
{
    m_changeToFirstPath = value;
}

void AddToArchive::setFilename(const KUrl& path)
{
    m_filename = path.pathOrUrl();
}

void AddToArchive::setMimeType(const QString & mimeType)
{
    m_mimeType = mimeType;
}

bool AddToArchive::showAddDialog(void)
{
    QPointer<Kerfuffle::AddDialog> dialog = new Kerfuffle::AddDialog(
        m_inputs, // itemsToAdd
        KUrl(m_firstPath), // startDir
        "", // filter
        NULL, // parent
        NULL); // widget

    bool ret = dialog->exec();

    if (ret) {
        kDebug() << "Returned URL:" << dialog->selectedUrl();
        kDebug() << "Returned mime:" << dialog->currentMimeFilter();
        setFilename(dialog->selectedUrl());
        setMimeType(dialog->currentMimeFilter());
    }

    delete dialog;

    return ret;
}

bool AddToArchive::addInput(const KUrl& url)
{
    m_inputs << url.pathOrUrl(
        QFileInfo(url.pathOrUrl()).isDir() ?
        KUrl::AddTrailingSlash :
        KUrl::RemoveTrailingSlash
    );

    if (m_firstPath.isEmpty()) {
        QString firstEntry = url.pathOrUrl(KUrl::RemoveTrailingSlash);
        m_firstPath = QFileInfo(firstEntry).dir().absolutePath();
    }

    return true;
}

void AddToArchive::start()
{
    QTimer::singleShot(0, this, SLOT(slotStartJob()));
}

// TODO: If this class should ever be called outside main.cpp,
//       the returns should be preceded by emitResult().
void AddToArchive::slotStartJob(void)
{
    kDebug();

    Kerfuffle::CompressionOptions options;

    if (!m_inputs.size()) {
        KMessageBox::error(NULL, i18n("No input files were given."));
        return;
    }

    Kerfuffle::Archive *archive;
    if (!m_filename.isEmpty()) {
        archive = Kerfuffle::factory(m_filename, m_mimeType);
        kDebug() << "Set filename to " + m_filename;
    } else {
        if (m_autoFilenameSuffix.isEmpty()) {
            KMessageBox::error(NULL, i18n("You need to either supply a filename for the archive or a suffix (such as rar, tar.gz) with the --autofilename argument."));
            return;
        }

        if (m_firstPath.isEmpty()) {
            kDebug() << "Weird, this should not happen. no firstpath defined. aborting";
            return;
        }

        QString base;
        QFileInfo fi(m_inputs.first());

        base = fi.absoluteFilePath();

        if (base.endsWith('/')) {
            base.chop(1);
        }

        QString finalName = base + '.' + m_autoFilenameSuffix;

        //if file already exists, append a number to the base until it doesn't
        //exist
        int appendNumber = 0;
        while (KStandardDirs::exists(finalName)) {
            ++appendNumber;
            finalName = base + '_' + QString::number(appendNumber) + '.' + m_autoFilenameSuffix;
        }

        kDebug() << "Autoset filename to " + finalName;
        archive = Kerfuffle::factory(finalName, m_mimeType);
    }

    // TODO Post-4.3 string freeze: the check for read-only must cause a separate error
    if (archive == NULL || archive->isReadOnly()) {
        KMessageBox::error(NULL, i18n("Failed to create the new archive. Permissions might not be sufficient."));
        return;
    }

    if (m_changeToFirstPath) {
        if (m_firstPath.isEmpty()) {
            kDebug() << "Weird, this should not happen. no firstpath defined. aborting";
            return;
        }

        const QDir stripDir(m_firstPath);

        for (int i = 0; i < m_inputs.size(); ++i) {
            m_inputs[i] = stripDir.absoluteFilePath(m_inputs.at(i));
        }

        options["GlobalWorkDir"] = stripDir.path();
        kDebug() << "Setting GlobalWorkDir to " << stripDir.path();
    }

    Kerfuffle::AddJob *job =
        archive->addFiles(m_inputs, options);

    KIO::getJobTracker()->registerJob(job);

    connect(job, SIGNAL(result(KJob*)),
            this, SLOT(slotFinished(KJob*)));

    job->start();
}

void AddToArchive::slotFinished(KJob *job)
{
    kDebug();

    if (job->error()) {
        KMessageBox::error(NULL, job->errorText());
    }

    emitResult();
}
}
