/***************************************************************************
 *   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/url.h"

#include <QUrl>

namespace Veneer
{

	// this comes mostly from KDE's kdelibs/kdecore/io/kurl.cpp:
	// Copyright (C) 1999 Torben Weis <weis@kde.org>
	// Copyright (C) 2005-2006 David Faure <faure@kde.org>
	QString Url::fileName() const
	{
		QString fname;

		const QString path = QUrl::path();
		int len = path.length();

		if (len == 0)
			return fname;

		while (len >= 1 && path[len - 1] == QLatin1Char('/'))
			len--;

		if (len == 1 && path[0] == QLatin1Char('/'))
			return fname;

		// Skip last n slashes
		int n = 1;
		int i = len;

		do
		{
			i = path.lastIndexOf(QLatin1Char('/'), i - 1);
		} while (--n && (i > 0));

		if (i == -1)
		{
			if (len == path.length())
				fname = path;
			else
				fname = path.left(len);
		}
		else
			fname = path.mid(i + 1, len - i - 1);

		return fname;
	}

	QString Url::url() const
	{
		return QString::fromLatin1(toEncoded());
	}

}
