/*
 * Copyright 2010  Jonas Emanuel Müller <zanoi@zanoi.net>
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 2 of 
 * the License, or (at your option) any later version.

 * 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 General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include "syndicationloader.h"
#include "loader.h"

#include <QString>
#include <QList>
#include <QModelIndex>
#include <QObject>

#include <KUrl>

namespace Videocatcher {

SyndicationLoader::SyndicationLoader(QString url)
{
    channelUrl = url;
}

SyndicationLoader::~SyndicationLoader()
{
}

void SyndicationLoader::load()
{
    Syndication::Loader *loader = Syndication::Loader::create();
    connect(loader, 
            SIGNAL(loadingComplete(Syndication::Loader*, Syndication::FeedPtr, Syndication::ErrorCode)),
            this, SLOT(syndicationLoadingComplete(Syndication::Loader*, Syndication::FeedPtr,
            Syndication::ErrorCode)));
    qDebug() << "passing the following URL to parser: " << channelUrl;
    loader->loadFrom(channelUrl);
}

void SyndicationLoader::syndicationLoadingComplete(Syndication::Loader* loader, Syndication::FeedPtr feed,
                                        Syndication::ErrorCode status)
{
    Q_UNUSED(loader);
    QString enclosureUrl;
    ErrorCode errorCode = Loader_Other_Error;;
    Channel* channel = new Channel;
    QList<Episode> channelEpisodes;
    QList<Syndication::ItemPtr> items;
    
    switch(status) {
    case  Syndication::Success:
        errorCode = Loader_Success;
        //FIXME: add author
        channel->setUrl(channelUrl);
        channel->setTitle(feed->title());
        channel->setAuthor("");
        channel->setWebsiteUrl(feed->link());

        items = feed->items();
        
        foreach(const Syndication::ItemPtr &item, items) {
            Episode episode;
            episode.title = item->title();
            if(Syndication::isHtml(episode.title)) {
                episode.title = Syndication::htmlToPlainText(episode.title);
            }

            episode.description = item->description();
            if(Syndication::isHtml(episode.description)) {
                episode.description = Syndication::htmlToPlainText(episode.description);
            }
            
            QList<Syndication::EnclosurePtr> enclosures = item->enclosures(); 
              
            if (enclosures.count() == 0) {
                qDebug() << "Found no enclosures. This seems to be a non-multimedia item";
            } else {
                foreach(const Syndication::EnclosurePtr &enclosure, enclosures) {
                    if(enclosure->type().startsWith(QLatin1String("audio")) || 
                       enclosure->type().startsWith(QLatin1String("video")) || 
                       enclosure->type() == QLatin1String("application/ogg") || 
                       enclosure->type() == QLatin1String("application/ogv") || 
                       enclosure->type() == QLatin1String("application/ogm")) {
                       episode.videoUrl = enclosure->url();
                       episode.videoSize = enclosure->length();
                    } else if (enclosure->type().isEmpty()) {
                        QString url = enclosure->url();
                        if(url.endsWith(QLatin1String(".ogg")) || 
                           url.endsWith(QLatin1String(".ogv")) || 
                           url.endsWith(QLatin1String(".oga")) || 
                           url.endsWith(QLatin1String(".mp3")) || 
                           url.endsWith(QLatin1String(".aac")) || 
                           url.endsWith(QLatin1String(".wav")) || 
                           url.endsWith(QLatin1String(".mp4")) || 
                           url.endsWith(QLatin1String(".mpg")) || 
                           url.endsWith(QLatin1String(".wmv")) || 
                           url.endsWith(QLatin1String("wma")) || 
                           url.endsWith(QLatin1String(".swf")) || 
                           url.endsWith(QLatin1String(".flv"))) {
                            episode.videoUrl = enclosure->url();
                            episode.videoSize = enclosure->length();
                        }
                    }
                }
            }
            
            episode.datePublished = (double)item->datePublished();
            
            channelEpisodes << episode;
        }
        channel->setEpisodes(channelEpisodes);
        break;
    case  Syndication::FileNotFound:
        errorCode = Loader_File_Not_Found;
        break;
    case Syndication::Timeout:
        break;
    case Syndication::UnknownHost:
        errorCode = Loader_Connection_Problem;
        break;
    case  Syndication::OtherRetrieverError:
        errorCode = Loader_Other_Error;
        break;
    case Syndication::Aborted:
        errorCode = Loader_Aborted;
        break;
    case Syndication::InvalidXml:
    case Syndication::XmlNotAccepted:
    case Syndication::InvalidFormat:
        errorCode = Loader_Parse_Error;
        break;
    }
    emit loadingComplete(channel, errorCode, channelUrl);
    delete channel;
    QObject::deleteLater();
}

} //namespace Videocatcher
