/**********************************************************************
 * 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 "importopml.h"
#include <QFileDialog>
#include <QMessageBox>
#include <QDomDocument>
#include <QTimer>
#include <util/sll/qtutil.h>
#include <util/sll/visitor.h>
#include <util/sll/either.h>
#include "opmlparser.h"

namespace LeechCraft
{
namespace Aggregator
{
	namespace
	{
		constexpr auto ItemUrlRole = Qt::UserRole;
	}

	ImportOPML::ImportOPML (const QString& file, QWidget *parent)
	: QDialog (parent)
	{
		Ui_.setupUi (this);
		Ui_.ButtonBox_->button (QDialogButtonBox::Open)->setEnabled (false);

		if (file.isEmpty ())
			on_Browse__released ();
		else
		{
			Ui_.File_->setText (file);
			on_File__textEdited (file);
		}
	}
	
	QString ImportOPML::GetFilename () const
	{
		return Ui_.File_->text ();
	}
	
	QString ImportOPML::GetTags () const
	{
		return Ui_.AdditionalTags_->text ().trimmed ();
	}
	
	QSet<QString> ImportOPML::GetSelectedUrls () const
	{
		QSet<QString> result;
	
		for (int i = 0, items = Ui_.FeedsToImport_->topLevelItemCount (); i < items; ++i)
		{
			const auto item = Ui_.FeedsToImport_->topLevelItem (i);
			if (item->data (0, Qt::CheckStateRole) == Qt::Checked)
				result << item->data (0, ItemUrlRole).toString ();
		}

		return result;
	}
	
	void ImportOPML::on_File__textEdited (const QString& newFilename)
	{
		if (QFile::exists (newFilename))
			HandleFile (newFilename);
		else
			Reset ();
	}
	
	void ImportOPML::on_Browse__released ()
	{
		auto startingPath = QFileInfo (Ui_.File_->text ()).path ();
		if (startingPath.isEmpty ())
			startingPath = QDir::homePath ();
	
		const auto& filename = QFileDialog::getOpenFileName (this,
				tr ("Select OPML file"),
				startingPath,
				tr ("OPML files (*.opml);;"
					"XML files (*.xml);;"
					"All files (*.*)"));
		if (filename.isEmpty ())
			return;

		Reset ();
	
		Ui_.File_->setText (filename);
	
		HandleFile (filename);
	}
	
	void ImportOPML::HandleFile (const QString& filename)
	{
		Util::Visit (ParseOPML (filename),
				[this] (const QString& error)
				{
					QMessageBox::critical (this, tr ("LeechCraft"), error);
					Reset ();
				},
				[this] (OPMLParser parser)
				{
					for (const auto& [name, value] : Util::Stlize (parser.GetInfo ()))
					{
						if (name == "title")
							Ui_.Title_->setText (value);
						else if (name == "dateCreated")
							Ui_.Created_->setText (value);
						else if (name == "dateModified")
							Ui_.Edited_->setText (value);
						else if (name == "ownerName")
							Ui_.Owner_->setText (value);
						else if (name == "ownerEmail")
							Ui_.OwnerEmail_->setText (value);
						else
							new QTreeWidgetItem (Ui_.OtherFields_, { name, value });
					}

					for (const auto& opmlItem : parser.Parse ())
					{
						const auto item = new QTreeWidgetItem (Ui_.FeedsToImport_, { opmlItem.Title_, opmlItem.URL_ });
						item->setData (0, Qt::CheckStateRole, Qt::Checked);
						item->setData (0, ItemUrlRole, opmlItem.URL_);
					}

					Ui_.ButtonBox_->button (QDialogButtonBox::Open)->setEnabled (true);
				});
	}
	
	void ImportOPML::Reset ()
	{
		Ui_.Title_->setText ("");
		Ui_.Created_->setText ("");
		Ui_.Edited_->setText ("");
		Ui_.Owner_->setText ("");
		Ui_.OwnerEmail_->setText ("");
		Ui_.OtherFields_->clear ();
		Ui_.FeedsToImport_->clear ();
	
		Ui_.ButtonBox_->button (QDialogButtonBox::Open)->setEnabled (false);
	}
}
}
