// Copyright (c) 2003 Charles Samuels <charles@kde.org>
// See the file COPYING for redistribution terms.

#include "file.h"
#include "selector.h"

#include <kfilemetainfo.h>
#include <kmimetype.h>


File::File(Base *base, FileId id)
{
	mBase = base;
	mId = id;

}

File::File(const File &ref)
{
	operator =(ref);
}

File::File()
{
	mBase=0;
	mId = 0;
}

File &File::operator=(const File &ref)
{
	mBase = ref.mBase;
	mId = ref.mId;

	return *this;
}

QString File::file() const
{
	return property("file");
}

KURL File::url() const
{
	KURL url;
	url.setPath(file());
	return url;
}

struct Map { const char *kfmi; const char *noatun; };
static const Map propertyMap[] =
{
	{ "Title", "title" },
	{ "Artist", "author" },
	{ "Album", "album" },
	{ "Genre", "genre" },
	{ "Tracknumber", "track" },
	{ "Date", "date" },
	{ "Comment", "comment" },
	{ "Location", "location" },
	{ "Organization", "organization" },
	{ "Bitrate", "bitrate" },
	{ "Sample Rate", "samplerate" },
	{ "Channels", "channels" },
	{ 0, 0 }
};

QString File::property(const QString &property) const
{
	QString str = base()->property(id(), property);

	unless (str.length() or property=="file")
	{
		// use KFMI
		KFileMetaInfo info(file());

		QCString ascii; // speed
		ascii = property.ascii();

		if (ascii == "mimetype")
		{
			KMimeType::Ptr p = KMimeType::findByPath(file());
			return p->name();
		}

		QString kname;
		for (int i=0; propertyMap[i].kfmi; i++)
		{
			if (propertyMap[i].noatun == ascii)
			{
				kname = propertyMap[i].kfmi;
			}
		}

		if (info.isValid() && kname.length())
			str = info.item(kname).string(false);
	}

	if (str=="---" || !str.stripWhiteSpace().length()) // why does KFMI suck?
		str = "";
	if (!str.length()) return QString::null;
	return str;
}

void File::setProperty(const QString &key, const QString &value)
{
	if (property(key) == value) return;
	base()->setProperty(id(), key, value);
	PlaylistItem p=new Item(*this);
	p.data()->modified();
}

void File::clearProperty(const QString &key)
{
	if (property(key).isNull()) return;
	base()->clearProperty(id(), key);
	PlaylistItem p=new Item(*this);
	p.data()->modified();
}

QStringList File::properties() const
{
	QStringList l = base()->properties(id());

	for (int i=0; propertyMap[i].noatun; i++)
	{
		if (property(propertyMap[i].noatun).length())
		{
			l += propertyMap[i].noatun;
		}
	}
	return l;
}

void File::setId(FileId id)
{
	base()->move(mId, id);
	mId = id;
}

void File::remove()
{
	PlaylistItem p=new Item(*this);
	p.data()->removed();
	mBase->remove(*this);
}

