/**********************************************************************
 * 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 "syncmanagerbase.h"
#include <QFileInfo>
#include <util/xpc/util.h>
#include "transcodemanager.h"
#include "../core.h"

namespace LeechCraft
{
namespace LMP
{
	SyncManagerBase::SyncManagerBase (QObject *parent)
	: QObject (parent)
	, Transcoder_ (new TranscodeManager (this))
	, TranscodedCount_ (0)
	, TotalTCCount_ (0)
	, WereTCErrors_ (false)
	, CopiedCount_ (0)
	, TotalCopyCount_ (0)
	{
		connect (Transcoder_,
				SIGNAL (fileStartedTranscoding (QString)),
				this,
				SLOT (handleStartedTranscoding (QString)));
		connect (Transcoder_,
				SIGNAL (fileReady (QString, QString, QString)),
				this,
				SLOT (handleFileTranscoded (QString, QString, QString)));
		connect (Transcoder_,
				SIGNAL (fileFailed (QString)),
				this,
				SLOT (handleFileTCFailed (QString)));
	}

	void SyncManagerBase::AddFiles (const QStringList& files, const TranscodingParams& params)
	{
		const int numFiles = files.size ();
		TotalTCCount_ += numFiles;
		TotalCopyCount_ += numFiles;

		emit transcodingProgress (TranscodedCount_, TotalTCCount_, this);
		emit uploadProgress (CopiedCount_, TotalCopyCount_, this);

		Transcoder_->Enqueue (files, params);

		emit uploadLog (tr ("Uploading %n file(s)", 0, numFiles));
	}

	void SyncManagerBase::CheckTCFinished ()
	{
		if (TranscodedCount_ < TotalTCCount_)
			return;

		if (WereTCErrors_)
		{
			const auto& e = Util::MakeNotification ("LMP",
					tr ("Files were transcoded, but some errors occured. "
						"Check the upload log for details."),
					Priority::Warning);
			Core::Instance ().SendEntity (e);
			WereTCErrors_ = false;
		}

		TotalTCCount_ = 0;
		TranscodedCount_ = 0;
	}

	void SyncManagerBase::CheckUploadFinished ()
	{
		if (CopiedCount_ < TotalCopyCount_)
			return;

		TotalCopyCount_ = 0;
		CopiedCount_ = 0;

		const auto& e = Util::MakeNotification ("LMP",
				tr ("Files finished uploading."),
				Priority::Info);
		Core::Instance ().SendEntity (e);
	}

	void SyncManagerBase::HandleFileTranscoded (const QString&, const QString&)
	{
		qDebug () << Q_FUNC_INFO << "file transcoded, gonna copy";
		emit transcodingProgress (++TranscodedCount_, TotalTCCount_, this);
		CheckTCFinished ();
	}

	void SyncManagerBase::handleStartedTranscoding (const QString& file)
	{
		emit uploadLog (tr ("File %1 started transcoding...")
				.arg ("<em>" + QFileInfo (file).fileName () + "</em>"));
	}

	void SyncManagerBase::handleFileTCFailed (const QString& file)
	{
		emit uploadLog (tr ("Transcoding of file %1 failed")
				.arg ("<em>" + QFileInfo (file).fileName () + "</em>"));
		WereTCErrors_ = true;

		emit transcodingProgress (TranscodedCount_, --TotalTCCount_, this);
		CheckTCFinished ();

		emit uploadProgress (CopiedCount_, --TotalCopyCount_, this);
		CheckUploadFinished ();
	}

	void SyncManagerBase::handleStartedCopying (const QString& file)
	{
		emit uploadLog (tr ("File %1 started copying...")
					.arg ("<em>" + QFileInfo (file).fileName () + "</em>"));
	}

	void SyncManagerBase::handleFinishedCopying ()
	{
		emit uploadLog (tr ("File finished copying"));

		emit uploadProgress (++CopiedCount_, TotalCopyCount_, this);
		emit singleUploadProgress (0, 0, this);
		CheckUploadFinished ();
	}

	void SyncManagerBase::handleCopyProgress (qint64 done, qint64 total)
	{
		emit singleUploadProgress (done, total, this);
	}

	void SyncManagerBase::handleErrorCopying (const QString& localPath, const QString& errorStr)
	{
		const auto& filename = QFileInfo (localPath).fileName ();
		const auto& text = tr ("Error copying file %1: %2.").arg (filename).arg (errorStr);

		Core::Instance ().SendEntity (Util::MakeNotification ("LMP",
					text,
					Priority::Warning));
		emit uploadLog (text);

		emit uploadProgress (++CopiedCount_, TotalCopyCount_, this);
		CheckUploadFinished ();
	}
}
}
