/**********************************************************************
 * 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 "transferjob.h"
#include <QFileInfo>
#include <QtDebug>
#include <msn/notificationserver.h>
#include "msnaccount.h"
#include "msnbuddyentry.h"
#include "zheetutil.h"
#include "callbacks.h"

namespace LeechCraft
{
namespace Azoth
{
namespace Zheet
{
	TransferJob::TransferJob (const MSN::fileTransferInvite& invite, Callbacks *cb, MSNAccount *acc)
	: QObject (acc)
	, ID_ (invite.sessionId)
	, A_ (acc)
	, CB_ (cb)
	, Buddy_ (acc->GetBuddy (ZheetUtil::FromStd (invite.userPassport)))
	, Dir_ (TransferDirection::TDIn)
	, Filename_ (ZheetUtil::FromStd (invite.friendlyname))
	, Done_ (0)
	, Total_ (invite.filesize)
	, State_ (TransferState::TSOffer)
	{
	}

	TransferJob::TransferJob (uint id, const QString& filename,
			MSNBuddyEntry *entry, Callbacks *cb, MSNAccount *acc)
	: QObject (acc)
	, ID_ (id)
	, A_ (acc)
	, CB_ (cb)
	, Buddy_ (entry)
	, Dir_ (TransferDirection::TDOut)
	, Filename_ (filename)
	, Done_ (0)
	, Total_ (QFileInfo (filename).size ())
	, State_ (TransferState::TSOffer)
	{
		connect (CB_,
				SIGNAL (fileTransferProgress (uint, quint64, quint64)),
				this,
				SLOT (handleProgress (uint, quint64, quint64)));
		connect (CB_,
				SIGNAL (fileTransferFailed (uint)),
				this,
				SLOT (handleFailed (uint)));
		connect (CB_,
				SIGNAL (fileTransferFinished (uint)),
				this,
				SLOT (handleFinished (uint)));
		connect (CB_,
				SIGNAL (fileTransferGotResponse (uint, bool)),
				this,
				SLOT (handleGotResponse (uint, bool)));
	}

	QString TransferJob::GetSourceID () const
	{
		return Buddy_->GetEntryID ();
	}

	QString TransferJob::GetName () const
	{
		return Filename_;
	}

	qint64 TransferJob::GetSize () const
	{
		return Total_;
	}

	QString TransferJob::GetComment () const
	{
		return QString ();
	}

	TransferDirection TransferJob::GetDirection () const
	{
		return Dir_;
	}

	void TransferJob::Accept (const QString& out)
	{
		if (Dir_ == TDOut)
		{
			qWarning () << Q_FUNC_INFO
					<< "can't accept outgoing transfer job";
			return;
		}

		auto sb = GetSB ();
		if (!sb)
		{
			qWarning () << Q_FUNC_INFO
					<< "got null SB for"
					<< Buddy_->GetHumanReadableID ();
			return;
		}

		Filename_ = out;
		sb->fileTransferResponse (ID_, ZheetUtil::ToStd (out), true);
	}

	void TransferJob::Abort ()
	{
		auto sb = GetSB ();
		if (!sb)
		{
			qWarning () << Q_FUNC_INFO
					<< "got null SB for"
					<< Buddy_->GetHumanReadableID ();
			return;
		}

		if (State_ != TSOffer || Dir_ == TDOut)
			sb->cancelFileTransfer (ID_);
		else if (Dir_ == TDIn)
			sb->fileTransferResponse (ID_, ZheetUtil::ToStd (Filename_), false);
	}

	MSN::SwitchboardServerConnection* TransferJob::GetSB () const
	{
		const auto& id = ZheetUtil::ToStd (Buddy_->GetHumanReadableID ());
		return A_->GetNSConnection ()->switchboardWithOnlyUser (id);
	}

	void TransferJob::handleProgress (uint id, quint64 done, quint64 total)
	{
		if (ID_ != id)
			return;

		Done_ = done;
		Total_ = total;
		emit transferProgress (done, total);
	}

	void TransferJob::handleFailed (uint id)
	{
		if (ID_ != id)
			return;

		State_ = TSFinished;
		emit errorAppeared (TEProtocolError, QString ());
	}

	void TransferJob::handleFinished (uint id)
	{
		if (ID_ != id)
			return;

		State_ = TSFinished;
		emit stateChanged (State_);
	}

	void TransferJob::handleGotResponse (uint id, bool resp)
	{
		if (ID_ != id)
			return;

		if (resp)
		{
			State_ = TSTransfer;
			emit stateChanged (State_);
		}
		else
		{
			State_ = TSFinished;
			emit errorAppeared (TEAborted, QString ());
		}
	}
}
}
}
