/***************************************************************************
 *   Copyright (C) 2008 by Ian Reinhart Geiser                             *
 *   geiseri@yahoo.com                                                     *
 *                                                                         *
 *   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, write to the                         *
 *   Free Software Foundation, Inc.,                                       *
 *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
 ***************************************************************************/
#include "rssprovider.h"
#include "urlfetch.h"
#include "remoteimagesourcedocument.h"

#include <QTimer>
#include <QSettings>
#include <QDomDocument>
#include <QDomNodeList>
#include <QPainter>
#include <QRectF>
#include <QWebPage>
#include <QWebFrame>
#include <QEventLoop>
#include <QApplication>
#include <QFontMetrics>

extern int qt_defaultDpi();

RSSProvider::RSSProvider(QObject *parent)
: QObject(parent), m_offset(0)
{
	m_desc = new QWebPage(this);
	connect( m_desc, SIGNAL(loadFinished(bool)), this, SLOT( renderWebPage() ));

	QTimer::singleShot( 0, this, SLOT(downloadNewFeed()));
}


RSSProvider::~RSSProvider()
{
}

void RSSProvider::printTextBox( const QRectF & box, QTextDocument * text, QPainter * painter )
{
        const qreal dpiScaleX =  qt_defaultDpi() / qreal(painter->device()->logicalDpiX());
        const qreal dpiScaleY =  qt_defaultDpi() / qreal(painter->device()->logicalDpiY());
        QSizeF nativeBoxSize( box.size().width() * dpiScaleX, box.size().height() * dpiScaleY);
        QSizeF pageSize = text->size();
        pageSize.scale(nativeBoxSize, Qt::KeepAspectRatio);
        const qreal textScaleX =  pageSize.width() / text->size().width();
        const qreal textScaleY =  pageSize.height() / text->size().height();

// 	painter->setPen(Qt::black);
// 	painter->drawRect( box );
	
        painter->save();
        painter->translate( box.x(), box.y() );
        painter->scale( 1.0/dpiScaleX,1.0/dpiScaleY);
        painter->scale( textScaleX, textScaleY);
        text->drawContents(painter);
        painter->restore();

}

void printImageBox( const QRectF & box, const QImage & img, QPainter * painter )
{
        QSizeF imgSize = img.size();
        QRectF boxRectAdjusted;
        qreal offsetX = box.x();
        qreal offsetY = box.y();

	imgSize.scale(box.width(), box.height(), Qt::KeepAspectRatio );
	boxRectAdjusted.setSize( imgSize );
	offsetX += ( box.width() - boxRectAdjusted.width() ) /2.0;
	offsetY += ( box.height() - boxRectAdjusted.height() )/2.0;

        painter->save();
        painter->translate( offsetX, offsetY );

        if( !img.isNull() )
                painter->drawImage(boxRectAdjusted, img);

        painter->restore();

}

void RSSProvider::renderWebPage()
{
	QSettings settings;
	QPixmap image(1280,960);
	QRectF titleImageBox( 10, 10, 1000, 50 );
	QRectF webImageBox(10, 70,1260,890);
	
	image.fill(Qt::white);
	
	RSSObject current = m_rss.at(m_offset);

	m_desc->mainFrame()->setScrollBarPolicy ( Qt::Vertical, Qt::ScrollBarAlwaysOff  );
	m_desc->mainFrame()->setScrollBarPolicy ( Qt::Horizontal, Qt::ScrollBarAlwaysOff  );
	m_desc->setViewportSize( webImageBox.size().toSize() );
	m_desc->mainFrame()->setTextSizeMultiplier(1.5);
	QImage webImage(m_desc->viewportSize(), QImage::Format_ARGB32);
	QPainter imagePainter(&webImage);
	m_desc->mainFrame()->render(&imagePainter);
	imagePainter.end();

		
	QPainter painter(&image);
	
	QTextDocument title;
	title.setHtml( current.title );
	
	printImageBox( webImageBox, webImage, &painter );
	printTextBox( titleImageBox, &title, &painter );
	
	painter.end();
	
	emit newImage(image);
	QTimer::singleShot( settings.value("RSS/Timeout", 5000).value<int>(), this, SLOT(timeout()));
	m_offset++;
}

void RSSProvider::generateWebImage( const QString &html, const QString &url  )
{
	QUrl qurl( url );
	m_desc->mainFrame()->setHtml( html, qurl );
}

void RSSProvider::timeout()
{
	QSettings settings;
	QString url = settings.value("RSS/Url").value<QString>();
	
	if( m_rss.size() <= m_offset )
		m_offset = 0;
	
	if( m_rss.size() == 0 )
		return;
	
	RSSObject current = m_rss.at(m_offset);
	generateWebImage( current.description, url );
}

void RSSProvider::downloadNewFeed()
{
	QSettings settings;
	QString url = settings.value("RSS/Url").value<QString>();
	if( url.isEmpty() )
		return;
	
	m_rss = parseRSS( URLFetch::fetch(  url  ) );
	timeout();
}

QList< RSSObject > RSSProvider::parseRSS(const QByteArray & xml) const
{
	QList<RSSObject> list;
	QDomDocument doc;
	QString errorMsg;
	int errorLine = 0;
	int errorColumn = 0;
	
	if( doc.setContent( xml, &errorMsg, &errorLine, &errorColumn ) )
	{
		QDomNodeList channels = doc.elementsByTagName("channel");
		for( int channelIdx = 0; channelIdx < channels.size(); ++channelIdx )
		{
			QDomElement channel = channels.item(channelIdx).toElement();
			if( !channel.isNull() )
			{
				QDomNodeList items = channel.elementsByTagName("item");
				for( int itemIdx = 0; itemIdx < items.size(); ++itemIdx )
				{
					QDomElement item = items.item(itemIdx).toElement();
					QString title = item.firstChildElement("title").text();
					QString desc = item.firstChildElement("description").text();
					
					list << RSSObject(QPixmap(), title, desc );
				}
			}
		}
	}
	return list;
}



