/*
 * Copyright 2013 Canonical Ltd.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of version 3 of the GNU Lesser General Public
 * License as published by the Free Software Foundation.
 *
 * 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 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.
 */

#include "downloader.h"
#include <QVariantMap>
#include "metatypes.h"
#include "network/network.h"

#define DOWNLOAD_COMMAND "post-download-command"
#define APP_ID "app_id"

namespace ClickPlugin {

Downloader::Downloader(QObject *parent) :
    QObject(parent)
{
    qDBusRegisterMetaType<StringMap>();
    qDBusRegisterMetaType<DownloadStruct>();
    qDBusRegisterMetaType<GroupDownloadStruct>();
    qDBusRegisterMetaType<StructList>();
    this->manager = new DownloadManager("com.canonical.applications.Downloader", "/", QDBusConnection::sessionBus(), 0);
}

void Downloader::startDownload(QString packagename, const QString& url, const QString& authHeader)
{
    QVariantMap vmap;
    QStringList args;
    args << "pkcon" << "-p" << "install-local" << "$file";
    vmap[DOWNLOAD_COMMAND] = args;
    vmap[APP_ID] = packagename;
    StringMap map;
    map[X_CLICK_TOKEN] = authHeader;
    DownloadStruct down = DownloadStruct(url, vmap, map);
    QDBusPendingReply<QDBusObjectPath> reply = this->manager->createDownload(down);
    reply.waitForFinished();
    if (reply.isError()) {
        emit this->downloadNotCreated(packagename, reply.error().message());
    }else{
        QDBusObjectPath path = reply.value();
        emit this->downloadCreated(packagename, path.path());
    }
}

}
