/*
 * Copyright (C) 2010 Canonical, Ltd.
 *
 * Authors:
 *  Olivier Tilloy <olivier.tilloy@canonical.com>
 *
 * This library is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License
 * as published by the Free Software Foundation; version 3.
 *
 * This library 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 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 "bamf-window.h"
#include "bamf-window-proxy.h"
#include "bamf-factory.h"

BamfWindow::BamfWindow(QString path) :
    BamfView(path), m_window_proxy(NULL)
{
    m_window_proxy = new OrgAyatanaBamfWindowInterface("org.ayatana.bamf", path,
                                                       QDBusConnection::sessionBus(),
                                                       static_cast<QObject*>(this));
    connect(this, SIGNAL(ActiveChanged(bool)),
            this, SLOT(OnActiveChanged(bool)));
}

BamfWindow::~BamfWindow()
{
    delete m_window_proxy;
}

BamfWindow *
BamfWindow::transient() const
{
    QDBusPendingReply<QString> reply = m_window_proxy->Transient();
    reply.waitForFinished();
    if (reply.isError()) {
        qWarning() << reply.error();
        return NULL;
    } else {
        BamfView *view = BamfFactory::get_default().view_for_path(reply.value());
        return qobject_cast<BamfWindow *>(view);
    }
}

uint
BamfWindow::xid() const
{
    QDBusPendingReply<uint> reply = m_window_proxy->GetXid();
    reply.waitForFinished();
    if (reply.isError()) {
        qWarning() << reply.error();
        return 0;
    } else {
        return reply.value();
    }
}

long
BamfWindow::last_active() const
{
    if (active()) {
        return time(NULL);
    }
    else {
        return m_last_active;
    }
}

void
BamfWindow::OnActiveChanged(bool new_state)
{
    if (!new_state) {
        m_last_active = time(NULL);
    }
}

