/**********************************************************************
 * 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 "userscriptcreator.h"

#include <QMessageBox>
#include <QFile>
#include <QInputDialog>
#include <QStandardPaths>
#include "createscriptdialog.h"
#include "userscript.h"
#include "fatape.h"

namespace LC
{
namespace Poshuku
{
namespace FatApe
{
	UserScriptCreator::UserScriptCreator (Plugin *plugin, QWidget *parent)
	: QObject { parent }
	, Plugin_ { plugin }
	, ParentWidget_ { parent }
	, Dia_ { std::make_shared<CreateScriptDialog> (parent) }
	{
		connect (Dia_.get (),
				SIGNAL (rejected ()),
				this,
				SLOT (deleteLater ()));
		connect (Dia_.get (),
				SIGNAL (accepted ()),
				this,
				SLOT (handleAccepted ()));

		Dia_->show ();
	}

	namespace
	{
		std::shared_ptr<QFile> CreateFile (const QString& scriptName, QWidget *parent)
		{
			const auto& temp = QStandardPaths::writableLocation (QStandardPaths::TempLocation);

			auto filename = scriptName;
			while (true)
			{
				const auto& fullPath = temp + '/' + filename + ".user.js";
				auto file = std::make_shared<QFile> (fullPath);
				if (file->open (QIODevice::WriteOnly))
					return file;

				if (QMessageBox::question (parent,
							"LeechCraft",
							UserScriptCreator::tr ("Unable to create file %1: %2. Do you want to try again changing the file name?")
								.arg ("<em>" + fullPath + "</em>")
								.arg (file->errorString ()),
							QMessageBox::Yes | QMessageBox::No) == QMessageBox::No)
					return {};

				filename = QInputDialog::getText (parent,
						"LeechCraft",
						UserScriptCreator::tr ("Enter new filename for the user script %1:")
							.arg ("<em>" + scriptName + "</em>"),
						QLineEdit::Normal,
						filename);
				if (filename.isEmpty ())
					return {};
			}
		}
	}

	QString UserScriptCreator::GenerateFile () const
	{
		const auto& file = CreateFile (Dia_->GetName (), ParentWidget_);
		if (!file)
			return {};

		const QStringList lines
		{
			"// ==UserScript==",
			"// @name           " + Dia_->GetName (),
			"// @namespace      " + Dia_->GetNamespace (),
			"// @description    " + Dia_->GetDescription (),
			"// @author         " + Dia_->GetAuthor (),
			"// ==/UserScript==",
			"(function() {",
			"})();"
		};

		for (const auto& line : lines)
		{
			file->write (line.toUtf8 ());
			file->write ("\n");
		}

		return file->fileName ();
	}

	void UserScriptCreator::handleAccepted ()
	{
		const auto& path = GenerateFile ();
		if (path.isEmpty ())
			return;

		UserScript script { path };
		script.Install ();
		Plugin_->EditScript (Plugin_->AddScriptToManager (script));
	}
}
}
}
