/*
 * newsfeedmanager.cpp
 *
 * Copyright (c) 2007 Frerich Raabe <raabe@kde.org>
 *
 * 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. For licensing and distribution details, check the
 * accompanying file 'COPYING'.
 */
#include "newsfeedmanager.h"

#include <kurl.h>

using namespace Syndication;

NewsFeedManager *NewsFeedManager::s_instance = 0;

NewsFeedManager *NewsFeedManager::self()
{
    if ( !s_instance ) {
        s_instance = new NewsFeedManager;
    }
    return s_instance;
}

NewsFeedManager::NewsFeedManager() : QObject()
{
}

void NewsFeedManager::setSubscriptions( const QStringList &urls )
{
    m_subscriptions = urls;
}

void NewsFeedManager::update()
{
    m_availableFeeds.clear();
    foreach ( const QString &url, m_subscriptions ) {
        updateFeed( url );
    }
}

void NewsFeedManager::updateFeed( const QUrl &url )
{
    Loader *loader = Loader::create( this, SLOT( loaderFinished( Syndication::Loader *, Syndication::FeedPtr, Syndication::ErrorCode ) ) );
    m_activeLoaders[ loader ] = url;
    loader->loadFrom( url );
}

const QMap<QUrl, FeedPtr> &NewsFeedManager::availableFeeds() const
{
    return m_availableFeeds;
}

void NewsFeedManager::loaderFinished( Loader *loader, FeedPtr feed, ErrorCode status )
{
    const QUrl url = m_activeLoaders[ loader ];
    m_activeLoaders.remove( loader );

    if ( status == Syndication::Success ) {
        m_availableFeeds[ url ] = feed;

        emit feedLoaded( url );
    }

    if ( m_activeLoaders.isEmpty() ) {
        emit updateFinished();
    }
}

#include "newsfeedmanager.moc"
