/*
 * 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-factory.h"
#include "bamf-view.h"
#include "bamf-application.h"
#include "bamf-window.h"
#include "bamf-indicator.h"

BamfFactory::BamfFactory() :
    m_views(NULL)
{
    m_views = new QHash<QString, BamfView*>();
}

BamfView *
BamfFactory::view_for_path(QString path)
{
    if (path.isEmpty())
        return NULL;

    if (m_views->contains(path))
        return m_views->value(path);

    BamfView *view = new BamfView(path);
    QString type = view->view_type();
    delete view;
    view = NULL;

    if (type == "application")
        view = static_cast<BamfView *>(new BamfApplication(path));
    else if (type == "window")
        view = static_cast<BamfView *>(new BamfWindow(path));
    else if (type == "indicator")
        view = static_cast<BamfView *>(new BamfIndicator(path));

    if (view != NULL)
    {
        m_views->insert(view->path(), view);
        connect(view, SIGNAL(destroyed(QObject *)), this, SLOT(OnViewDestroyed(QObject *)));
        connect(view, SIGNAL(Closed()), this, SLOT(OnViewClosed()));
    }

    return view;
}

void
BamfFactory::OnViewDestroyed(QObject * view)
{
    m_views->remove(m_views->key(static_cast<BamfView *>(view)));
}

void
BamfFactory::OnViewClosed()
{
    sender()->deleteLater();
}

