/***************************************************************************
 *   Copyright (C) 2010 by Volker Lanz <vl@fidra.de>                       *
 *                                                                         *
 *   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.,                                       *
 *   51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA            *
 ***************************************************************************/

#include "veneer/system.h"

#include <qglobal.h>
#include <QCoreApplication>
#include <QStringList>
#include <QDir>
#include <QFile>
#include <QDebug>

namespace Veneer
{
	QString defaultDataWriteDir()
	{
		QString rval;

#if defined(Q_OS_WIN32)
		rval = QString(qgetenv("APPDATA")) + QDir::separator() + QCoreApplication::organizationName() + QDir::separator() + QCoreApplication::applicationName() + QDir::separator();
#elif defined(Q_OS_MAC)
		rval = QDir::homePath() + "/Library/Application Support/" + QCoreApplication::applicationName() + QDir::separator();
#else // UNIX
		QStringList dataDirPaths = QString(qgetenv("XDG_DATA_HOME")).split(':', QString::SkipEmptyParts);

		if (dataDirPaths.isEmpty())
			dataDirPaths << QDir::homePath() + QDir::separator() + ".local/share/apps/";

		rval = dataDirPaths[0] + QDir::separator() + QCoreApplication::applicationName().toLower() + QDir::separator();
#endif

		rval = QDir::cleanPath(rval);

// 		qDebug() << "default data write dir: " << rval;

		return rval;
	}

	QString findFilePath(const QString& fileName)
	{
		QStringList dataDirs = findDataDirPaths();

		foreach (const QString& dir, dataDirs)
			if (QFile::exists(dir + QDir::separator() + fileName))
				return dir + QDir::separator() + fileName;

		return defaultDataWriteDir() + QDir::separator() + fileName;
	}

	QString findExistingFilePath(const QString& fileName)
	{
		QStringList dataDirs = findDataDirPaths();

		foreach (const QString& dir, dataDirs)
			if (QFile::exists(dir + QDir::separator() + fileName))
				return dir + QDir::separator() + fileName;

		return QString();
	}

	QStringList findDataDirPaths()
	{
		QStringList dataDirPaths = QString(qgetenv("XDG_DATA_HOME")).split(':', QString::SkipEmptyParts);

		if (dataDirPaths.isEmpty())
			dataDirPaths << QDir::homePath() + QDir::separator() + ".local/share/apps/";

		dataDirPaths << QString(qgetenv("XDG_DATA_DIRS")).split(':', QString::SkipEmptyParts);

#if defined(Q_OS_WIN32)
		dataDirPaths
			<< QString(qgetenv("APPDATA")) + QDir::separator() + QCoreApplication::organizationName() + QDir::separator() + QCoreApplication::applicationName()
			<< QCoreApplication::applicationDirPath();
#elif defined(Q_OS_MAC)
		dataDirPaths
			<< QDir::homePath() + "/Library/Application Support/" + QCoreApplication::applicationName() + QDir::separator()
			<< QCoreApplication::applicationDirPath();
#else // UNIX
		dataDirPaths << QString("/usr/share/apps/") + QCoreApplication::applicationName().toLower() + QDir::separator();
#endif

		QString appDir = QCoreApplication::applicationDirPath();
		int binpos = appDir.lastIndexOf("/bin");

		if (binpos >= 0)
		{
			appDir.replace(binpos, 4, "/share/apps/");
			appDir.append(QCoreApplication::applicationName().toLower() + QDir::separator());
			dataDirPaths << appDir;
		}

		// add resource path
		dataDirPaths << ":/data/";

		// clean up
		QStringList::Iterator i = dataDirPaths.begin();

		while (i != dataDirPaths.end())
		{
			*i = QDir::cleanPath(*i);

			if (!i->endsWith(QDir::separator()) && !i->endsWith('/'))
				i->append(QDir::separator());

			if (!QFile::exists(*i))
			{
// 				qDebug() << "does not exist: " << *i;
				i = dataDirPaths.erase(i);
			}
			else
				i++;
		}

		dataDirPaths.removeDuplicates();

// 		qDebug() << dataDirPaths;

		return dataDirPaths;
	}
}
