/*
 * 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.
 */

#ifndef CLICKMANAGER_H
#define CLICKMANAGER_H

#include <QQuickItem>
#include <QHash>
#include <QList>
#include <QVariant>
#include <QVariantList>
#include "application.h"
#include <token.h>

#ifdef TESTS
#include "fakeprocess.h"
#include "fakenetwork.h"
#include "fakedownloader.h"
#include "testclickmanager.h"
#include "fakessoservice.h"
#else
#include <ssoservice.h>
#include <QProcess>
#include "network/network.h"
#include "download/downloader.h"
#endif

using namespace UbuntuOne;

namespace ClickPlugin {

class ClickManager : public QQuickItem
{
    Q_OBJECT
    Q_DISABLE_COPY(ClickManager)
    Q_PROPERTY(QVariantList model READ model NOTIFY modelChanged)

#ifdef TESTS
    friend class TestClickManager;
#endif

signals:
    void modelChanged();
    void updatesNotFound();
    void credentialsNotFound();
    void updateAvailableFound();
    void errorFound();
    
public:
    ClickManager(QQuickItem *parent = 0);
    ~ClickManager();

    Q_INVOKABLE void checkUpdates();
    Q_INVOKABLE void startDownload(QString packagename);

    QVariantList model() const { return this->m_model; }

private slots:
    void processOutput();
    void processUpdates();
    void downloadUrlObtained(QString packagename, QString url);
    void downloadCreated(QString packagename, QString dbuspath);
    void downloadNotCreated(QString packagename, QString error);
    void handleCredentialsFound(Token token);
    void handleCredentialsNotFound();
    void clickTokenReceived(Application* app, const QString& clickToken);

private:
    QHash<QString, Application*> m_apps;
    QVariantList m_model;
    Token m_token;
#ifdef TESTS
    FakeSsoService m_service;
    FakeNetwork m_network;
    FakeDownloader downloader;
    FakeProcess m_process;
#else
    SSOService m_service;
    QProcess m_process;
    Network m_network;
    Downloader downloader;
#endif

    void checkForUpdates();
};

}

QML_DECLARE_TYPE(ClickPlugin::ClickManager)

#endif // CLICKMANAGER_H

