/**********************************************************************
 * LeechCraft - modular cross-platform feature rich internet client.
 * Copyright (C) 2006-2013  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 <interfaces/core/icoreproxy.h>
#include <interfaces/core/irootwindowsmanager.h>
#include "shooterdialog.h"
#include "poster.h"

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

		Util::InstallTranslator ("auscrie");

		Dialog_ = new ShooterDialog ();

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

	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 screenshoter.");
	}

	QIcon Plugin::GetIcon () const
	{
		static QIcon icon (":/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::makeScreenshot ()
	{
		Dialog_->setVisible (!Dialog_->ShouldHide ());

		ShotAction_->setEnabled (false);
		const int add = Dialog_->GetTimeout () ? 0 : 200;
		QTimer::singleShot (Dialog_->GetTimeout () * 1000 + add,
				this,
				SLOT (shoot ()));
	}

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

		auto mw = Proxy_->GetRootWindowsManager ()->GetPreferredWindow ();

		const QPixmap& pm = GetPixmap ();
		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:
			{
				QByteArray bytes;
				QBuffer buf (&bytes);
				buf.open (QIODevice::ReadWrite);
				if (!pm.save (&buf,
							qPrintable (Dialog_->GetFormat ()),
							quality))
					qWarning () << Q_FUNC_INFO
						<< "save failed"
						<< qPrintable (Dialog_->GetFormat ())
						<< quality;
				Post (bytes);
				break;
			}
		}
	}

	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 ());
		}

		qWarning () << Q_FUNC_INFO
				<< "unknown mode";
		return QPixmap ();
	}

	void Plugin::Post (const QByteArray& data)
	{
		Poster *p = new Poster (Dialog_->GetHostingService (),
				data,
				Dialog_->GetFormat (),
				Proxy_->GetNetworkAccessManager ());
		connect (p,
				SIGNAL (gotEntity (const LeechCraft::Entity&)),
				this,
				SIGNAL (gotEntity (const LeechCraft::Entity&)));
	}
}
}

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