/*
 * Copyright 2008 Arthur Renato Mello <arthur@mandriva.com>
 * Copyright 2008 Gustavo Pichorim Boiko <boiko@mandriva.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 3 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., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 */

#include <QDir>
#include <QList>
#include <QPixmap>

#include <KConfig>
#include <KConfigGroup>
#include <KGlobal>
#include <KStandardDirs>
#include <KLocale>

#include "themesettings.h"

ThemeSettings::ThemeSettings(const QString &p_theme, const QSize &p_target)
{
	m_targetSize = p_target;

	if(p_theme.isEmpty())
	{
		KConfig cfg("ksplashrc");

		if(cfg.hasGroup("KSplash"))
		{
			KConfigGroup g = cfg.group("KSplash");
			m_themeName = g.readEntry("Theme", "MgaDefault");
		}
		else
			m_themeName = "MgaDefault";
	}
	else
		m_themeName = p_theme;

	m_themePath = KGlobal::dirs()->locate("data",
		"ksplash/Themes/" + m_themeName + "/Theme.rc");
	m_themePath = m_themePath.left(m_themePath.lastIndexOf("/") + 1);

	//TODO: define start icons
	m_imagesDefault.append("kded");
	m_imagesDefault.append("confupdate");
	m_imagesDefault.append("kcminit");
	m_imagesDefault.append("ksmserver");
	m_imagesDefault.append("wm");
	m_imagesDefault.append("desktop");
	m_imagesDefault.append("ready");

	m_stepsDefault.append("kded");
	m_stepsDefault.append("confupdate");
	m_stepsDefault.append("kcminit");
	m_stepsDefault.append("ksmserver");
	m_stepsDefault.append("wm");
	m_stepsDefault.append("desktop");
	m_stepsDefault.append("ready");

	m_imagesTexts["kded"] = i18n("Starting Generic Services Daemon");
	m_imagesTexts["confupdate"] = i18n("Starting Configuration Manager");
	m_imagesTexts["kcminit"] = i18n("Starting Initialization Services Manager");
	m_imagesTexts["ksmserver"] = i18n("Starting Session Manager");
	m_imagesTexts["wm"] = i18n("Starting Window Manager");
	m_imagesTexts["desktop"] = i18n("Initializing Desktop Environment");
	m_imagesTexts["ready"] = i18n("Desktop Environment Running");

	readSettings();

	chooseResolution();
	
	m_imageLoader.setBaseSize(m_baseSize);
	m_imageLoader.setTargetSize(m_targetSize);
	m_imageLoader.setCachePrefix("ksplash/cache/" + m_themeName);

	if(!m_statusFile.isEmpty())
		loadStatusInfo();
}

ThemeSettings::~ThemeSettings()
{
}

void ThemeSettings::readSettings()
{
	QString themeFile(m_themePath + "Theme.rc");

	KConfig cfg(themeFile, KConfig::FullConfig);

	if(!cfg.hasGroup("KSplash Theme: " + m_themeName))
		return;

	KConfigGroup group = cfg.group("KSplash Theme: " + m_themeName);

	m_bg = group.readEntry("Background", QString()).trimmed();
	m_baseSize = group.readEntry("BaseResolution", QSize());

	m_svgFileNormal = group.readEntry("SVGFile", QString()).trimmed();
	m_svgFileWide = group.readEntry("SVGFileWide", QString()).trimmed();

	m_statusFile = group.readEntry("Status", QString()).trimmed();
	m_statusInfo.font = group.readEntry("StatusFont", QFont("Helvetica", 12));
	m_statusInfo.color = group.readEntry("StatusColor", QColor(Qt::white));

	QPoint statusCoord = group.readEntry("StatusCoords", QPoint(0, 0));
	QSize statusSize = group.readEntry("StatusRectSize", QSize(200, 100));

	m_statusInfo.rect = QRect(statusCoord, statusSize);

	m_useIconSet = group.readEntry("UseIconSet", true);
	m_items = group.readEntry("AnimationItems", m_imagesDefault.count());

	for(int i = 0; i < m_items; i++)
	{
		m_images.append(group.readEntry(QString("Image%1").arg(i+1),
										m_imagesDefault[i]).trimmed());		

		m_steps.append(group.readEntry(QString("ImageStep%1").arg(i+1),
									   m_stepsDefault[i]).trimmed());

		m_imagesCoords.append(group.readEntry(QString("ImageCoords%1").arg(i+1),											  QPoint()));	

	}

	QMapIterator<QString, QString> i(m_imagesTexts);

	while(i.hasNext())
	{
		i.next();
		QString text = group.readEntry(QString("Status-%1").arg(i.key()),
									   QString()).trimmed();
		
		if(!text.isNull())
			m_imagesTexts[i.key()] = text;
	}
}

void ThemeSettings::chooseResolution()
{
	if(!m_svgFileNormal.isEmpty())
		m_svgFile = m_svgFileNormal;

	if(!m_svgFileWide.isEmpty())
	{
		QSize normal = m_imageLoader.getSVGSize(m_themePath + m_svgFileNormal);
		QSize wide = m_imageLoader.getSVGSize(m_themePath + m_svgFileNormal);

		double desktopRatio = (double) m_targetSize.width() /
			m_targetSize.height();

		double normalDiff = desktopRatio -
			((double) normal.width() / normal.height());

		double wideDiff = desktopRatio -
			((double) wide.width() / wide.height());

		if(normalDiff < 0)
			normalDiff *= -1;

		if(wideDiff < 0)
			wideDiff *= -1;

		if(wideDiff < normalDiff)
			m_svgFile = m_svgFileWide;
	}
}

void ThemeSettings::loadStatusInfo()
{
	QString statusFile;

	if(!m_svgFile.isEmpty() && m_statusFile.startsWith(":"))
		statusFile = m_svgFile + m_statusFile;
	else
		statusFile = m_statusFile;

	m_statusInfo.rect = m_imageLoader.loadStatusRect(m_themePath +
													 statusFile);
}

QMap<QString, QString> ThemeSettings::getStatusTexts()
{
	return m_imagesTexts;
}

statusInfo ThemeSettings::getStatusInfo()
{
	return m_statusInfo;
}

QPixmap ThemeSettings::getBackground()
{
	QString bg;

	if(!m_svgFile.isEmpty() && m_bg.startsWith(":"))
		bg = m_svgFile + m_bg;
	else
		bg = m_bg;

	return m_imageLoader.loadBackground(m_themePath + bg);
}

itemsList ThemeSettings::getItemsList()
{
	itemsList list;

	for(int i = 0; i < m_images.size(); i++)
	{
		loadedItem item;

		if(m_images.at(i) == m_imagesDefault.at(i))
			item.pixmap = m_imageLoader.loadItem(m_themePath +
						 						 m_imagesDefault.at(i),
												 m_imagesCoords.at(i), true);
		else
		{
			QString itemFile;

			if( !m_svgFile.isEmpty() && m_images.at(i).startsWith(":"))
				itemFile = m_svgFile + m_images.at(i);
			else
				itemFile = m_images.at(i);

			item.pixmap = m_imageLoader.loadItem(m_themePath + itemFile,
												 m_imagesCoords.at(i));
		}

		item.step = m_steps.at(i);

		list.append(item);
	}

	return list;
}