/* This file is part of libhud-qt
 * Copyright 2013 Canonical Ltd.
 *
 * libhud-qt is free software: you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License version 3,
 * as published by the Free Software Foundation.
 *
 * libhud-qt is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranties of
 * MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR
 * PURPOSE.  See the GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include "hud.h"

// needed for glib includes.
#undef signals
#include <libhud-2/hud.h>

using namespace Ubuntu::HUD;

class Ubuntu::HUD::HUD::Private : public QObject
{
    Q_OBJECT

public:
    QList<Context *> contexts;
    QString activeContext;

    HudManager *manager;
};


HUD::HUD(QObject *parent)
    : QObject(parent)
{
    d = new Private;

    g_type_init();
    d->manager = 0;
}


HUD::~HUD()
{
    g_clear_object (&d->manager);
    delete d;
}


QList<Context *>
HUD::contexts()
{
    return d->contexts;
}

void
HUD::setActiveContext(Context *context)
{
    if (!d->contexts.contains(context)) {
        qWarning("Tried to activate context that has not been added to HUD.");
        return;
    }
    HudActionPublisher *publisher;
    publisher = context->publisher();
    hud_manager_switch_window_context(d->manager, publisher);
}

void
HUD::_register(const QString &application_idenfier)
{
    if (d->manager != 0) {
        qDebug("Already registered to HUD.");
        return;
    }

    if (application_idenfier.isEmpty()) {
        qWarning("Refusing to register to HUD with empty application identifer.");
        return;
    }

    d->manager = hud_manager_new(qPrintable(application_idenfier));
    foreach (Context *ctx, d->contexts) {
        HudActionPublisher *publisher;
        publisher = ctx->publisher();
        hud_manager_add_actions(d->manager, publisher);
    }
}

void
HUD::addContext(Context *context)
{
    if (d->contexts.contains(context)) {
        qWarning("Trying to add Context that already exist in HUD");
        return;
    }

    /*! @todo ownership */
    d->contexts.append(context);
    emit contextAdded(context);
    emit contextsChanged();

    if (d->manager != 0) {
        // we have manager, add the context there
        HudActionPublisher *publisher;
        publisher = context->publisher();
        hud_manager_add_actions(d->manager, publisher);
    }
}

void
HUD::removeContext(Context *context)
{
    if (!d->contexts.contains(context)) {
        qWarning("Trying to remove Context that does not exist in HUD.");
        return;
    }

    d->contexts.removeOne(context);
    emit contextRemoved(context);
    emit contextsChanged();
}

#include "hud.moc"
