/**********************************************************************
 * 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 "auscrie.h"
#include <QMainWindow>
#include <QIcon>
#include <QTimer>
#include <QBuffer>
#include <QDir>
#include <QFileDialog>
#include <QDesktopWidget>
#include <xmlsettingsdialog/basesettingsmanager.h>
#include <util/util.h>
#include <util/xpc/util.h>
#include <util/sll/unreachable.h>
#include <interfaces/core/icoreproxy.h>
#include <interfaces/core/irootwindowsmanager.h>
#include <interfaces/ientityhandler.h>
#include "shooterdialog.h"
#include "util.h"

namespace LeechCraft
{
namespace Auscrie
{
	void Plugin::Init (ICoreProxy_ptr proxy)
	{
		Proxy_ = proxy;

		Util::InstallTranslator ("auscrie");

		Dialog_ = new ShooterDialog (proxy);

		ShotAction_ = new QAction (GetIcon (),
				tr ("Make a screenshot"),
				this);
		connect (ShotAction_,
				SIGNAL (triggered ()),
				this,
				SLOT (showDialog ()));
		connect (Dialog_,
				SIGNAL (screenshotRequested ()),
				this,
				SLOT (makeScreenshot ()),
				Qt::QueuedConnection);
		connect (Dialog_,
				SIGNAL (accepted ()),
				this,
				SLOT (performAction ()));
	}

	void Plugin::SecondInit ()
	{
	}

	void Plugin::Release ()
	{
	}

	QByteArray Plugin::GetUniqueID () const
	{
		return "org.LeechCraft.Auscrie";
	}

	QString Plugin::GetName () const
	{
		return "Auscrie";
	}

	QString Plugin::GetInfo () const
	{
		return tr ("Simple auto screenshotter.");
	}

	QIcon Plugin::GetIcon () const
	{
		static QIcon icon ("lcicons:/resources/images/auscrie.svg");
		return icon;
	}

	QList<QAction*> Plugin::GetActions (ActionsEmbedPlace place) const
	{
		QList<QAction*> result;

		if (place == ActionsEmbedPlace::CommonContextMenu)
			result << ShotAction_;

		return result;
	}

	void Plugin::showDialog ()
	{
		MakeScreenshot (0);
	}

	void Plugin::makeScreenshot ()
	{
		MakeScreenshot (Dialog_->GetTimeout () * 1000);
	}

	void Plugin::performAction ()
	{
		const auto& pm = Dialog_->GetScreenshot ();
		if (pm.isNull ())
			return;

		auto mw = Proxy_->GetRootWindowsManager ()->GetPreferredWindow ();
		const int quality = Dialog_->GetQuality ();

		switch (Dialog_->GetAction ())
		{
		case ShooterDialog::Action::Save:
		{
			QString path = Proxy_->GetSettingsManager ()->
				Property ("PluginsStorage/Auscrie/SavePath",
						QDir::currentPath () + "01." + Dialog_->GetFormat ())
				.toString ();

			QString filename = QFileDialog::getSaveFileName (mw,
					tr ("Save as"),
					path,
					tr ("%1 files (*.%1);;All files (*.*)")
						.arg (Dialog_->GetFormat ()));

			if (!filename.isEmpty ())
			{
				pm.save (filename,
						qPrintable (Dialog_->GetFormat ()),
						quality);
				Proxy_->GetSettingsManager ()->
					setProperty ("PluginsStorage/Auscrie/SavePath",
							filename);
			}
			break;
		}
		case ShooterDialog::Action::Upload:
		{
			const auto& info = Dialog_->GetDFInfo ();
			if (!info.Object_)
			{
				qWarning () << Q_FUNC_INFO
						<< "no object set";
				break;
			}

			auto e = Util::MakeEntity (pm.toImage (),
					{}, {}, "x-leechcraft/data-filter-request");
			e.Additional_ ["Format"] = Dialog_->GetFormat ();
			e.Additional_ ["Quality"] = quality;
			e.Additional_ ["DataFilter"] = info.Variant_;

			auto ieh = qobject_cast<IEntityHandler*> (info.Object_);
			ieh->Handle (e);

			const auto iinfo = qobject_cast<IInfo*> (info.Object_);
			SaveFilterState ({ iinfo->GetUniqueID (), info.Variant_ });

			break;
		}
		}
	}

	void Plugin::shoot ()
	{
		ShotAction_->setEnabled (true);

		const QPixmap& pm = GetPixmap ();
		Dialog_->show ();
		Dialog_->SetScreenshot (pm);
	}

	void Plugin::MakeScreenshot (int timeout)
	{
		Dialog_->setVisible (!Dialog_->ShouldHide ());

		ShotAction_->setEnabled (false);
		QTimer::singleShot (std::max (timeout, 200),
				this,
				SLOT (shoot ()));
	}

	QPixmap Plugin::GetPixmap () const
	{
		auto rootWin = Proxy_->GetRootWindowsManager ()->GetPreferredWindow ();

		switch (Dialog_->GetMode ())
		{
		case ShooterDialog::Mode::LCWindowOverlay:
			return QPixmap::grabWindow (rootWin->winId ());
		case ShooterDialog::Mode::LCWindow:
			return QPixmap::grabWidget (rootWin);
		case ShooterDialog::Mode::CurrentScreen:
		{
 			auto desk = qApp->desktop ();
			auto screen = desk->screen (desk->screenNumber (QCursor::pos ()));
			auto geom = desk->screenGeometry (QCursor::pos ());
			return QPixmap::grabWindow (screen->winId (),
					geom.x (), geom.y (), geom.width (), geom.height ());
		}
		case ShooterDialog::Mode::WholeDesktop:
			return QPixmap::grabWindow (qApp->desktop ()->winId ());
		}

		Util::Unreachable ();
	}
}
}

LC_EXPORT_PLUGIN (leechcraft_auscrie, LeechCraft::Auscrie::Plugin);
