/**********************************************************************
 * LeechCraft - modular cross-platform feature rich internet client.
 * Copyright (C) 2010  Vadim Misbakh-Soloviev, 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 "contentsdisplaydialog.h"
#include <QStandardItemModel>
#include <util/sll/qtutil.h>
#include <util/xpc/introspectable.h>
#include <interfaces/iinfo.h>
#include "interfaces/secman/istorageplugin.h"
#include "core.h"

namespace LeechCraft
{
namespace SecMan
{
	namespace
	{
		QString Unserialize (const QVariant& var)
		{
			if (var.canConvert<QString> ())
				return var.toString ();
			else if (var.canConvert<QByteArray> ())
				return var.toByteArray ();
			else if (var.canConvert<int> ())
				return QString::number (var.toInt ());
			else if (var.canConvert<double> ())
				return QString::number (var.toDouble ());
			else if (var.canConvert<QVariantList> ())
			{
				QStringList subvars;
				for (const auto& sv : var.toStringList ())
					subvars << Unserialize (sv);
				return "ByteArray { " + subvars.join ("; ") + " }";
			}
			else if (var.canConvert<QVariantMap> ())
			{
				QStringList subvars;
				for (const auto& pair : Util::Stlize (var.toMap ()))
					subvars << "{ " + pair.first + " -> " + Unserialize (pair.second) + "}";
				return "Map { " + subvars.join ("; ") + " }";
			}
			else
			{
				try
				{
					return Unserialize (Util::Introspectable::Instance () (var));
				}
				catch (const std::exception& e)
				{
					qWarning () << Q_FUNC_INFO
							<< e.what ();
				}

				qWarning () << Q_FUNC_INFO
						<< "unsupported data type"
						<< var
						<< var.typeName ()
						<< var.userType ()
						<< var.toString ();
				return QString ("unsupported datatype %1 (%2) (%3), loading the matching plugin may help")
						.arg (var.typeName ())
						.arg (var.userType ())
						.arg (var.toString ());
			}
		}
	}

	ContentsDisplayDialog::ContentsDisplayDialog (QWidget *parent)
	: QDialog { parent }
	, ContentsModel_ { new QStandardItemModel { this } }
	{
		Ui_.setupUi (this);

		ContentsModel_->setHorizontalHeaderLabels ({ tr ("Key index"), tr ("Value") });
		Ui_.ContentsTree_->setModel (ContentsModel_);

		auto makePair = [] (const QString& leftText, const QString& rightText)
		{
			const QList<QStandardItem*> result
			{
				new QStandardItem { leftText },
				new QStandardItem { rightText }
			};
			for (const auto item : result)
				item->setEditable (false);
			return result;
		};

		for (auto pluginObj : Core::Instance ().GetStoragePlugins ())
		{
			auto ii = qobject_cast<IInfo*> (pluginObj);
			auto isp = qobject_cast<IStoragePlugin*> (pluginObj);

			auto pluginItems = makePair (ii->GetName (), ii->GetInfo ());

			for (const auto& key : isp->ListKeys ())
			{
				const auto& valList = isp->Load (key);
				const auto& keyPair = makePair (QString::fromUtf8 (key), {});
				pluginItems.first ()->appendRow (keyPair);
				int valIndex = 0;
				for (const auto& valVar : valList.toList ())
				{
					const auto& str = Unserialize (valVar);
					keyPair.first ()->appendRow (makePair (QString::number (++valIndex), str));
				}
			}

			ContentsModel_->appendRow (pluginItems);
		}

		Ui_.ContentsTree_->expandAll ();
	}
}
}
