/*
Copyright (c) 2008-2009 Jaagup Rep�n

Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
*/


#include "plasma-tvprogramme.h"
#include <iostream>
#include <fstream>
#include <string>
#include <map>
#include <ctime>
#include <QtXml>
#include <QtCore>
#include <QtGui>
#include <KConfigDialog>
#include <KConfig>
#include <KStandardDirs>
#include <KIO/NetAccess>
#include <Plasma/Theme>
using namespace std;

PlasmaTvProgramme::PlasmaTvProgramme(QObject *parent, const QVariantList &args)
	: Plasma::Applet(parent, args)
{
	setBackgroundHints(DefaultBackground);
	setAspectRatioMode(Plasma::IgnoreAspectRatio);
	resize(1000, 100);
	setHasConfigurationInterface(true);
}


PlasmaTvProgramme::~PlasmaTvProgramme()
{
	if (!hasFailedToLaunch())
	{
		KConfigGroup configGroup = globalConfig();
		configGroup.writeEntry("TextColor", textColor);
		configGroup.writeEntry("TitleColor", titleColor);
		configGroup.writeEntry("GridColor", gridColor);
		configGroup.writeEntry("TitleIsBold", boldTitle);
		configGroup.writeEntry("VerticalGrid", verticalGrid);
		configGroup.writeEntry("HorizontalGrid", horizontalGrid);
		configGroup.writeEntry("ShowIcons", showIcons);
		configGroup.writeEntry("XMLTVs", xmltvs);
		configGroup.writeEntry("ShowAllChannels", showAllChannels);
		configGroup.writeEntry("Channels", channelsToShow);
	}
}

void PlasmaTvProgramme::init()
{
	KConfigGroup configGroup = globalConfig();
	textColor = configGroup.readEntry("TextColor", QColor(Qt::white));
	titleColor = configGroup.readEntry("TitleColor", QColor(Qt::white));
	gridColor = configGroup.readEntry("GridColor", QColor(Qt::white));
	boldTitle = configGroup.readEntry("TitleIsBold", true);
	verticalGrid = configGroup.readEntry("VerticalGrid", true);
	horizontalGrid = configGroup.readEntry("HorizontalGrid", true);
	showIcons = configGroup.readEntry("ShowIcons", true);
	xmltvs = configGroup.readEntry("XMLTVs", QStringList());
	showAllChannels = configGroup.readEntry("ShowAllChannels", true);
	channelsToShow = configGroup.readEntry("Channels", QStringList());
	dataEngine("time")->connectSource("Local", this, 60000, Plasma::AlignToMinute);
	dataDir = KStandardDirs::locateLocal("data", "plasma_tvprogramme/", true);
	reparse();
}

void PlasmaTvProgramme::paintInterface(QPainter *p, const QStyleOptionGraphicsItem*, const QRect &contentsRect)
{
	const int left   = contentsRect.left(),
		  top    = contentsRect.top(),
		  width  = contentsRect.width(),
		  height = contentsRect.height(),
		  count  = channels.count();
	float cx = 0;
	if (count > 0)
	{
		cx = width / count;
	}
	p->setRenderHint(QPainter::SmoothPixmapTransform);
	p->setRenderHint(QPainter::Antialiasing);
	p->save();
	QFont font(p->font());

	font.setBold(boldTitle);
	p->setFont(font);
	p->setPen(titleColor);
	for (int i = 0; i < count; i++)
	{
		if ((channels[i].icon.isNull()) || (!showIcons))
		{
			p->drawText(left + cx * i, top, cx - 10, 20,
					Qt::AlignLeft | Qt::AlignTop, text(i, 0));
		}
		else
		{
			p->drawImage(left + cx * i, top, channels[i].icon);
			p->drawText(left + cx * i + channels[i].icon.width() + 5, top, cx - 10, 20,
					Qt::AlignLeft | Qt::AlignTop, text(i, 0));
		}
	}

	font.setBold(false);
	p->setFont(font);
	p->setPen(textColor);
	for (int i = 0; i < count; i++)
	{
		for (int j = 1; j < height / 20; j++)
		{
			p->drawText(left + cx * i, top + 20 * j, cx - 10,
					20, Qt::AlignLeft | Qt::AlignTop, text(i, j));
		}
	}

	p->setPen(gridColor);
	if (horizontalGrid)
	{
		p->drawLine(left, top + 18, left + width, top + 18);
	}
	if (verticalGrid)
	{
		for (int i = 1; i < count; i++)
		{
			p->drawLine(left + cx * i - 5, top, left + cx * i - 5, top + height);
		}
	}

	p->restore();
}

void PlasmaTvProgramme::createConfigurationInterface(KConfigDialog *parent)
{
	QWidget *widgetXmltvs = new QWidget;
	QWidget *widgetChannels = new QWidget;
	QWidget *widgetAppearance = new QWidget;
	uiXmltvs.setupUi(widgetXmltvs);
	uiChannels.setupUi(widgetChannels);
	uiAppearance.setupUi(widgetAppearance);
	parent->setButtons(KDialog::Ok | KDialog::Cancel);
	connect(parent, SIGNAL(okClicked()), this, SLOT(configAccepted()));
	parent->addPage(widgetXmltvs, i18n("XMLTVs"), icon());
	parent->addPage(widgetChannels, i18n("Channels"), icon());
	parent->addPage(widgetAppearance, i18n("Appearance"), icon());
	uiXmltvs.xmltvs->setItems(xmltvs);
	uiChannels.showAllChannels->setChecked(showAllChannels);
	uiChannels.channels->setItems(channelsToShow);
	uiAppearance.textColor->setColor(textColor);
	uiAppearance.titleColor->setColor(titleColor);
	uiAppearance.gridColor->setColor(gridColor);
	uiAppearance.boldTitle->setChecked(boldTitle);
	uiAppearance.verticalGrid->setChecked(verticalGrid);
	uiAppearance.horizontalGrid->setChecked(horizontalGrid);
	uiAppearance.showIcons->setChecked(showIcons);
}

void PlasmaTvProgramme::configAccepted()
{
	QStringList xmltvsOld = xmltvs;
	xmltvs = uiXmltvs.xmltvs->items();
	showAllChannels = uiChannels.showAllChannels->isChecked();
	channelsToShow = uiChannels.channels->items();
	textColor = uiAppearance.textColor->color();
	titleColor = uiAppearance.titleColor->color();
	gridColor = uiAppearance.gridColor->color();
	boldTitle = uiAppearance.boldTitle->isChecked();
	verticalGrid = uiAppearance.verticalGrid->isChecked();
	horizontalGrid = uiAppearance.horizontalGrid->isChecked();
	showIcons = uiAppearance.showIcons->isChecked();
	QString xmltv;
	foreach (xmltv, xmltvsOld)
	{
		if (!xmltvs.contains(xmltv))
		{
			QString str = dataDir + basename(xmltv.toAscii().data());
			remove(str.toAscii().data());
			QString icon;
			foreach (icon, icons.value(xmltv))
			{
				remove(icon.toAscii().data());
			}
		}
	}
	reparse();
}

void PlasmaTvProgramme::reparse()
{
	channels.clear();
	icons.clear();
	for (int xmltv = 0; xmltv < xmltvs.count(); xmltv++)
	{
		bool isOld = false, error = false, wasOld = false;
		int defaultChannel = 0;
		QDomElement element;
		QDomNodeList nodes, nodes2;
		QDomNamedNodeMap attributes;
		map<QString,int> channelMap;
		QString filename = dataDir + basename(xmltvs[xmltv].toAscii().data());
		do {
			if (isOld)
			{
				wasOld = true;
			}
			struct stat st;
			if (stat(filename.toAscii().data(), &st) != 0 || isOld)
			{
				KIO::NetAccess::download(KUrl(xmltvs.at(xmltv)), filename, NULL);
				isOld = false;
			}
			QDomDocument doc;
			QFile file(filename);
			if (!doc.setContent(&file))
			{
				error = true;
			}
			element = doc.documentElement();
			nodes = element.elementsByTagName("programme");
			if (nodes.count() > 0)
			{
				QString qstr = nodes.at(nodes.count() - 1).attributes().namedItem("start").nodeValue();
				string timeThen = string(qstr.toAscii().data()).substr(0, 14);
				time_t rawtime;
				struct tm *timeinfo;
				char cstr[30];
				QString ret;
				time(&rawtime);
				rawtime += 86400; // one day
				timeinfo = localtime(&rawtime);
				strftime(cstr, 30, "%Y%m%d%H%M%S", timeinfo);
				string timeNeeded(cstr);
				if (timeThen < timeNeeded)
				{
					isOld = true;
				}
			}
			else
			{
				isOld = true;
			}
		} while (isOld && !error && !wasOld);
		if (error)
		{
			continue;
		}
		nodes = element.elementsByTagName("channel");
		if (nodes.count() == 0)
		{
			return;
		}
		for (int nodeNumber = 0; nodeNumber < nodes.count(); nodeNumber++)
		{
			Channel channel;
			attributes = nodes.at(nodeNumber).attributes();
			channel.id = attributes.namedItem("id").nodeValue();
			nodes2 = nodes.at(nodeNumber).childNodes();
			for (int node2Number = 0; node2Number < nodes2.count(); node2Number++)
			{
				if ((nodes2.at(node2Number).nodeName() == "display-name") && (channel.name.isNull()))
				{
					channel.name = nodes2.at(node2Number).toElement().text();
				}
				if ((nodes2.at(node2Number).nodeName() == "icon") &&
					(channel.icon.isNull()) &&
					((showAllChannels) || (channelsToShow.contains(channel.name))))
				{
					QString str = nodes2.at(node2Number).attributes().namedItem("src").nodeValue();
					filename = dataDir + basename(str.toAscii().data());
					struct stat st;
					if (stat(filename.toAscii().data(), &st) != 0)
					{
						KIO::NetAccess::download(str, filename, NULL);
					}
					channel.icon.load(filename);
					channel.icon = channel.icon.scaledToHeight(15);
					icons[xmltvs[xmltv]].append(filename);
				}
			}
			if ((showAllChannels) || (channelsToShow.contains(channel.name)))
			{
				channels.append(channel);
				channelMap[channel.id] = channels.count() - 1;
				defaultChannel         = channels.count() - 1;
			}
		}
		nodes = element.elementsByTagName("programme");
		for (int nodeNumber = 0; nodeNumber < nodes.count(); nodeNumber++)
		{
			QDomNode node;
			Program program;
			program.channel = defaultChannel;
			attributes = nodes.at(nodeNumber).attributes();
			node = attributes.namedItem("channel");
			if (!node.isNull())
			{
				// if channel is not in list skip this programm
				if (channelMap.find(node.nodeValue()) == channelMap.end())
				{
					continue;
				}
				program.channel = channelMap[node.nodeValue()];
			}
			node = attributes.namedItem("start");
			if (!node.isNull())
			{
				string str(node.nodeValue().toAscii().data());
				program.time = str.substr(0, 14);
			}
			nodes2 = nodes.at(nodeNumber).childNodes();
			for (int node2Number = 0; node2Number < nodes2.count(); node2Number++)
			{
				if (nodes2.at(node2Number).nodeName() == "title")
				{
					program.name = nodes2.at(node2Number).toElement().text().toAscii().data();
				}
			}
			channels[program.channel].programs.append(program);
		}
	}
}

QString PlasmaTvProgramme::text(int channel, int program, bool tryAgain)
{
	if (program == 0)
	{
		return channels[channel].name;
	}
	time_t rawtime;
	struct tm *timeinfo;
	char cstr[30];
	QString ret;
	time(&rawtime);
	timeinfo = localtime(&rawtime);
	strftime(cstr, 30, "%Y%m%d%H%M%S", timeinfo);
	string time(cstr);
	int number = 0;
	QList<Program>::iterator it, endIterator = channels[channel].programs.end();
	for(it = channels[channel].programs.begin(); it != endIterator; ++it)
	{
		if (time < (*it).time)
		{
			number++;
			if (number == program)
			{
				return ret;
			}
		}
		ret = (*it).time.substr(8, 2).c_str();
		ret += ":";
		ret += (*it).time.substr(10, 2).c_str();
		ret += " ";
		ret += (*it).name;
	}
	if (tryAgain)
	{
		reparse();
		text(channel, program, false);
	}
	return "Data is old";
}

#include "plasma-tvprogramme.moc"
