#include "widgets.h"


namespace Dict {

DatabaseView::DatabaseView(QWidget *parent)
	: QListWidget(parent)
{
	setSelectionMode(QAbstractItemView::MultiSelection);
	connect(this, SIGNAL(itemSelectionChanged()), SLOT(selection()));
}

void DatabaseView::selection()
{
	emit selected(current());
}

QStringList DatabaseView::current(bool all)
{
	QStringList list;
	for (int i = 0; i < count(); ++i)
		if (all || item(i)->isSelected())
			list << item(i)->data(Qt::UserRole).toString();
	return list;
}

void DatabaseView::setList(const List &list, const QStringList &selected)
{
	blockSignals(true);
	clear();
	blockSignals(false);
	foreach (Pair pair, list)
		addItem(elide(pair.second));
	for (int i = 0; i < count(); ++i)
		item(i)->setData(Qt::UserRole, list[i].first);
	setCurrent(selected);
}

QString DatabaseView::data(int index) const
{
	return item(index)->data(Qt::UserRole).toString();
}

void DatabaseView::setCurrent(const QStringList &list)
{
	blockSignals(true);
	for (int i = 0; i < count(); ++i)
		item(i)->setSelected(list.contains(data(i)));
	blockSignals(false);
}

const DatabaseList DatabaseView::list() const
{
	DatabaseList itemlist;
	for (int i = 0; i < count(); ++i)
		itemlist << item(i);
	return itemlist;
}


DatabaseMenu::DatabaseMenu(QObject *parent)
	: InfoMenu(parent)
{
	group = new QActionGroup(this);
}

void DatabaseMenu::setGroups(const GroupList &list, QAction *dbedit)
{
	QString text;
	if (group->checkedAction())
		text = group->checkedAction()->text().remove('&');

	foreach (QAction *action, group->actions())
		group->removeAction(action);
	menu()->clear();

	addAction(i18n("First Match"), QStringList(Connection::DefaultDatabase));
	addAction(i18n("All Databases"), QStringList(Connection::AllDatabases));
	addAction(i18n("Database List"), QStringList());

	addSeparator();
	foreach (GroupPair pair, list)
		addAction(pair.first, pair.second);

	foreach (QAction *action, menu()->actions()) {
		action->setCheckable(true);
		if (!action->isSeparator())
			group->addAction(action);
		if (action->text() == text)
			action->setChecked(true);
	}
	if (!group->checkedAction()) setChecked(0);
	addSeparator();
	KActionMenu::addAction(dbedit);
}

void DatabaseMenu::actionTriggered(QAction *action)
{
	if (action->actionGroup() == group) {
		emit selected(action->data().toStringList());
		emit selected(group->actions().indexOf(action));
	}
}

void DatabaseMenu::setChecked(int select)
{
	if (select < 0 || select >= group->actions().size()) select = 0;
	group->actions().at(select)->setChecked(true);
}

int DatabaseMenu::checked() const
{
	QAction *checked = group->checkedAction();
	return (checked) ? group->actions().indexOf(checked) : 0;
}

QStringList DatabaseMenu::current() const
{
	QAction *action = group->checkedAction();
	return action->data().toStringList();
}

void DatabaseMenu::setList(const QStringList &list, bool active)
{
	group->actions().at(2)->setData(list);
	if (active) setChecked(2);
}

}
