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

namespace LeechCraft
{
namespace Aggregator
{
	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 ();
	}
	
	std::vector<bool> ImportOPML::GetMask () const
	{
		std::vector<bool> result (Ui_.FeedsToImport_->topLevelItemCount ());
	
		for (int i = 0, items = Ui_.FeedsToImport_->topLevelItemCount (); i < items; ++i)
			result [i] = Ui_.FeedsToImport_->topLevelItem (i)->data (0, Qt::CheckStateRole) == Qt::Checked;
	
		return result;
	}
	
	void ImportOPML::on_File__textEdited (const QString& newFilename)
	{
		Reset ();
	
		if (QFile (newFilename).exists ())
			Ui_.ButtonBox_->button (QDialogButtonBox::Open)->
				setEnabled (HandleFile (newFilename));
		else
			Reset ();
	}
	
	void ImportOPML::on_Browse__released ()
	{
		QString startingPath = QFileInfo (Ui_.File_->text ()).path ();
		if (startingPath.isEmpty ())
			startingPath = QDir::homePath ();
	
		QString filename = QFileDialog::getOpenFileName (this,
				tr ("Select OPML file"),
				startingPath,
				tr ("OPML files (*.opml);;"
					"XML files (*.xml);;"
					"All files (*.*)"));
	
		if (filename.isEmpty ())
		{
			QTimer::singleShot (0,
					this,
					SLOT (reject ()));
			return;
		}
	
		Reset ();
	
		Ui_.File_->setText (filename);
	
		Ui_.ButtonBox_->button (QDialogButtonBox::Open)->
			setEnabled (HandleFile (filename));
	}
	
	bool ImportOPML::HandleFile (const QString& filename)
	{
		QFile file (filename);
		if (!file.open (QIODevice::ReadOnly))
		{
			QMessageBox::critical (this,
					tr ("LeechCraft"),
					tr ("Could not open file %1 for reading.")
						.arg (filename));
			return false;
		}
	
		QByteArray data = file.readAll ();
		file.close ();
	
		QString errorMsg;
		int errorLine, errorColumn;
		QDomDocument document;
		if (!document.setContent (data,
					true,
					&errorMsg,
					&errorLine,
					&errorColumn))
		{
			QMessageBox::critical (this,
					tr ("LeechCraft"),
					tr ("XML error, file %1, line %2, column %3, error:<br />%4")
						.arg (filename)
						.arg (errorLine)
						.arg (errorColumn)
						.arg (errorMsg));
			return false;
		}
	
		OPMLParser parser (document);
		if (!parser.IsValid ())
		{
			QMessageBox::critical (this,
					tr ("LeechCraft"),
					tr ("OPML from file %1 is not valid.")
						.arg (filename));
			return false;
		}
	
		OPMLParser::OPMLinfo_t info = parser.GetInfo ();
	
		for (OPMLParser::OPMLinfo_t::const_iterator i = info.begin (),
				end = info.end (); i != end; ++i)
		{
			QString name = i.key ();
			QString value = i.value ();
	
			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
			{
				QStringList strings;
				strings << name << value;
				new QTreeWidgetItem (Ui_.OtherFields_, strings);
			}
		}
	
		OPMLParser::items_container_t items = parser.Parse ();
		for (OPMLParser::items_container_t::const_iterator i = items.begin (),
				end = items.end (); i != end; ++i)
		{
			QStringList strings;
			strings << i->Title_ << i->URL_;
			QTreeWidgetItem *item =
				new QTreeWidgetItem (Ui_.FeedsToImport_, strings);
			item->setData (0, Qt::CheckStateRole, Qt::Checked);
		}
	
		return 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);
	}
}
}
