/**********************************************************************
 * LeechCraft - modular cross-platform feature rich internet client.
 * Copyright (C) 2006-2014  Georg Rudoy
 *
 * Boost Software License - Version 1.0 - August 17th, 2003
 *
 * Permission is hereby granted, free of charge, to any person or organization
 * obtaining a copy of the software and accompanying documentation covered by
 * this license (the "Software") to use, reproduce, display, distribute,
 * execute, and transmit the Software, and to prepare derivative works of the
 * Software, and to permit third-parties to whom the Software is furnished to
 * do so, all subject to the following:
 *
 * The copyright notices in the Software and this entire statement, including
 * the above license grant, this restriction and the following disclaimer,
 * must be included in all copies of the Software, in whole or in part, and
 * all derivative works of the Software, unless such copies or derivative
 * works are solely in the form of machine-executable object code generated by
 * a source language processor.
 *
 * 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, TITLE AND NON-INFRINGEMENT. IN NO EVENT
 * SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
 * FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
 * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 **********************************************************************/

#include "localfileresolver.h"
#include <QtDebug>
#include <QFileInfo>
#include <taglib/fileref.h>
#include <taglib/tag.h>

namespace LeechCraft
{
namespace LMP
{
	ResolveError::ResolveError (const QString& path, const std::string& what)
	: runtime_error (what)
	, Path_ (path)
	{
	}

	ResolveError::~ResolveError () throw ()
	{
	}

	QString ResolveError::GetPath () const
	{
		return Path_;
	}

	LocalFileResolver::LocalFileResolver (QObject *parent)
	: QObject (parent)
	{
	}

	TagLib::FileRef LocalFileResolver::GetFileRef (const QString& file) const
	{
#ifdef Q_OS_WIN32
		return TagLib::FileRef (reinterpret_cast<const wchar_t*> (file.utf16 ()));
#else
		return TagLib::FileRef (file.toUtf8 ().constData (), true, TagLib::AudioProperties::Accurate);
#endif
	}

	MediaInfo LocalFileResolver::ResolveInfo (const QString& file)
	{
		const auto& modified = QFileInfo (file).lastModified ();
		{
			QReadLocker locker (&CacheLock_);
			if (Cache_.contains (file))
			{
				const auto& pair = Cache_ [file];
				if (pair.first == modified)
					return pair.second;
			}
		}

		QMutexLocker tlLocker (&TaglibMutex_);

		auto r = GetFileRef (file);
		auto tag = r.tag ();
		if (!tag)
			throw ResolveError (file, "failed to get file tags");

		auto audio = r.audioProperties ();

		auto ftl = [] (const TagLib::String& str) { return QString::fromUtf8 (str.toCString (true)); };
		auto genres = ftl (tag->genre ()).split ('/', QString::SkipEmptyParts);
		std::for_each (genres.begin (), genres.end (),
				[] (QString& genre) { genre = genre.trimmed (); });

		MediaInfo info
		{
			file,
			ftl (tag->artist ()),
			ftl (tag->album ()),
			ftl (tag->title ()),
			genres,
			audio ? audio->length () : 0,
			static_cast<qint32> (tag->year ()),
			static_cast<qint32> (tag->track ())
		};
		{
			QWriteLocker locker (&CacheLock_);
			if (Cache_.size () > 200)
				Cache_.clear ();
			Cache_ [file] = qMakePair (modified, info);
		}
		return info;
	}

	QMutex& LocalFileResolver::GetMutex ()
	{
		return TaglibMutex_;
	}
}
}
