/**********************************************************************
 * 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 "bookmarkswidget.h"
#include <QMessageBox>
#include <util/models/flattofoldersproxymodel.h>
#include <interfaces/core/icoreproxy.h>
#include <interfaces/core/itagsmanager.h>
#include "core.h"
#include "favoritesdelegate.h"
#include "favoritesmodel.h"
#include "xmlsettingsmanager.h"

namespace LeechCraft
{
namespace Poshuku
{
	BookmarksWidget::BookmarksWidget (QWidget *parent)
	: QWidget (parent)
	{
		Ui_.setupUi (this);

		FavoritesFilterModel_.reset (new FilterModel (this));
		FavoritesFilterModel_->setSourceModel (Core::Instance ().GetFavoritesModel ());
		FavoritesFilterModel_->setDynamicSortFilter (true);

		FlatToFolders_.reset (new Util::FlatToFoldersProxyModel (this));
		FlatToFolders_->SetTagsManager (Core::Instance ()
				.GetProxy ()->GetTagsManager ());
		handleGroupBookmarks ();
		XmlSettingsManager::Instance ()->RegisterObject ("GroupBookmarksByTags",
				this, "handleGroupBookmarks");

		Ui_.FavoritesView_->setItemDelegate (new FavoritesDelegate (this));
		Ui_.FavoritesView_->addAction (Ui_.ActionEditBookmark_);
		Ui_.FavoritesView_->addAction (Ui_.ActionDeleteBookmark_);
		connect (Ui_.FavoritesView_,
				SIGNAL (deleteSelected (const QModelIndex&)),
				this,
				SLOT (translateRemoveFavoritesItem (const QModelIndex&)));

		FavoritesFilterLineCompleter_.reset (
				new Util::TagsCompleter (Ui_.FavoritesFilterLine_, this)
				);
		Ui_.FavoritesFilterLine_->AddSelector ();
		connect (Ui_.FavoritesFilterLine_,
				SIGNAL (tagsChosen ()),
				this,
				SLOT (selectTagsMode ()));
		connect (Ui_.FavoritesFilterLine_,
				SIGNAL (textChanged (const QString&)),
				this,
				SLOT (updateFavoritesFilter ()));
		connect (Ui_.FavoritesFilterType_,
				SIGNAL (currentIndexChanged (int)),
				this,
				SLOT (updateFavoritesFilter ()));
		connect (Ui_.FavoritesFilterCaseSensitivity_,
				SIGNAL (stateChanged (int)),
				this,
				SLOT (updateFavoritesFilter ()));

		QHeaderView *itemsHeader = Ui_.FavoritesView_->header ();
		QFontMetrics fm = fontMetrics ();
		itemsHeader->resizeSection (0,
				fm.width ("Average site title can be very big, it's also the "
					"most important part, so it's priority is the biggest."));
		itemsHeader->resizeSection (1,
				fm.width ("Average URL could be very very long, but we don't account this."));
		itemsHeader->resizeSection (2,
				fm.width ("Average tags list size should be like this."));
	}

	void BookmarksWidget::on_ActionEditBookmark__triggered ()
	{
		auto current = Ui_.FavoritesView_->selectionModel ()->currentIndex ();
		if (FlatToFolders_->GetSourceModel ())
			current = FlatToFolders_->MapToSource (current);
		if (!current.isValid ())
			return;

		Core::Instance ().GetFavoritesModel ()->EditBookmark (FavoritesFilterModel_->mapToSource (current));
	}

	void BookmarksWidget::on_ActionDeleteBookmark__triggered ()
	{
		QModelIndex current = Ui_.FavoritesView_->
			selectionModel ()->currentIndex ();
		if (!current.isValid ())
			return;

		translateRemoveFavoritesItem (current);
	}

	void BookmarksWidget::translateRemoveFavoritesItem (const QModelIndex& sourceIndex)
	{
		QModelIndex index = sourceIndex;
		if (FlatToFolders_->GetSourceModel ())
		{
			index = FlatToFolders_->MapToSource (index);
			if (!index.isValid ())
			{
				QList<QPersistentModelIndex> toDelete;
				for (int i = 0, rows = FlatToFolders_->rowCount (sourceIndex);
						i < rows; ++i)
				{
					index = FlatToFolders_->index (i, 0, sourceIndex);
					index = FlatToFolders_->MapToSource (index);
					index = FavoritesFilterModel_->mapToSource (index);
					toDelete << QPersistentModelIndex (index);
				}

				Q_FOREACH (const QPersistentModelIndex& pIndex, toDelete)
					Core::Instance ().GetFavoritesModel ()->removeItem (pIndex);

				return;
			}
		}
		index = FavoritesFilterModel_->mapToSource (index);
		Core::Instance ().GetFavoritesModel ()->removeItem (index);
	}

	void BookmarksWidget::updateFavoritesFilter ()
	{
		int section = Ui_.FavoritesFilterType_->currentIndex ();
		QString text = Ui_.FavoritesFilterLine_->text ();

		switch (section)
		{
			case 1:
				FavoritesFilterModel_->setTagsMode (false);
				FavoritesFilterModel_->setFilterWildcard (text);
				break;
			case 2:
				FavoritesFilterModel_->setTagsMode (false);
				FavoritesFilterModel_->setFilterRegExp (text);
				break;
			case 3:
				FavoritesFilterModel_->setTagsMode (true);
				FavoritesFilterModel_->setFilterFixedString (text);
				break;
			default:
				FavoritesFilterModel_->setTagsMode (false);
				FavoritesFilterModel_->setFilterFixedString (text);
				break;
		}

		FavoritesFilterModel_->
			setFilterCaseSensitivity ((Ui_.FavoritesFilterCaseSensitivity_->
						checkState () == Qt::Checked) ? Qt::CaseSensitive :
					Qt::CaseInsensitive);
	}

	void BookmarksWidget::on_FavoritesView__activated (const QModelIndex& act)
	{
		QModelIndex index;
		if (FlatToFolders_->GetSourceModel ())
			index = FlatToFolders_->MapToSource (act);

		Ui_.ActionEditBookmark_->setEnabled (index.isValid ());
		Ui_.ActionDeleteBookmark_->setEnabled (index.isValid ());

		if (index.isValid ())
			Core::Instance ().NewURL (index.sibling (index.row (),
						FavoritesModel::ColumnURL).data ().toString ());
		else if (act.isValid ())
			for (int i = 0, size = FlatToFolders_->rowCount (act);
					i < size; ++i)
			{
				QModelIndex idx = FlatToFolders_->
					index (i, FavoritesModel::ColumnURL, act);
				Core::Instance ().NewURL (FlatToFolders_->
						MapToSource (idx).data ().toString ());
			}
	}

	void BookmarksWidget::on_OpenInTabs__released ()
	{
		for (int i = 0, size = FavoritesFilterModel_->rowCount ();
				i < size; ++i)
			Core::Instance ().NewURL (FavoritesFilterModel_->
					index (i, FavoritesModel::ColumnURL).data ().toString ());
	}

	void BookmarksWidget::selectTagsMode ()
	{
		Ui_.FavoritesFilterType_->setCurrentIndex (3);
		updateFavoritesFilter ();
	}

	void BookmarksWidget::handleGroupBookmarks ()
	{
		if (XmlSettingsManager::Instance ()->
				property ("GroupBookmarksByTags").toBool ())
		{
			FlatToFolders_->SetSourceModel (FavoritesFilterModel_.get ());
			Ui_.FavoritesView_->setModel (FlatToFolders_.get ());
		}
		else
		{
			FlatToFolders_->SetSourceModel (0);
			Ui_.FavoritesView_->setModel (FavoritesFilterModel_.get ());
		}
	}
}
}
