#include "widgets.h"

#include <QToolBar>


namespace Dict {

Select::Select(QObject *parent)
	: KSelectAction(parent), combobox(0) {}

QString Select::current() const
{
	return (currentItem() >= 0 && actions().count())
		? currentAction()->data().toString() : 0;
}

void Select::setCurrent(const QString &data)
{
	foreach (QAction *action, actions())
		if (action->data().toString() == data) {
			setCurrentAction(action);
			if (combobox) combobox->setCurrentIndex(currentItem());
		}
}

void Select::setList(const List &list, const QString &selected)
{
	clear();
	foreach (Pair pair, list) {
		addAction(elide(pair.second))->setData(pair.first);
		if (combobox) combobox->addItem(pair.first);
	}
	setCurrent(selected);
	setEnabled(!list.isEmpty());
}

void Select::clear()
{
	KSelectAction::clear();
	if (combobox) combobox->clear();
}

void Select::setEnabled(bool enabled)
{
	KSelectAction::setEnabled(enabled);
	if (combobox) combobox->setEnabled(enabled);
}

void Select::setFocus()
{
	if (combobox) combobox->setFocus();
}

void Select::actionTriggered(QAction *action)
{
	emit textTriggered(action->data().toString());
	emit indexTriggered(currentItem());
}

QWidget *Select::createWidget(QWidget *parent)
{
	if (!qobject_cast<QToolBar *>(parent))
		return KSelectAction::createWidget(parent);

	combobox = new QComboBox(parent);
	combobox->setMaxVisibleItems(20);
	combobox->setSizeAdjustPolicy(QComboBox::AdjustToContents);

	connect(combobox, SIGNAL(currentIndexChanged(const QString &)),
		SLOT(setCurrent(const QString &)));
	connect(this, SIGNAL(indexTriggered(int)),
		combobox, SLOT(setCurrentIndex(int)));
	connect(combobox, SIGNAL(activated(const QString &)),
		SIGNAL(textTriggered(const QString &)));

	int index = currentItem();
	foreach (QAction *action, actions())
		combobox->addItem(action->data().toString());
	combobox->setCurrentIndex(index);

	combobox->setEnabled(combobox->count());
	combobox->setToolTip(text().remove('&'));

	return combobox;
}

void Select::deleteWidget(QWidget *)
{
	delete combobox;
	combobox = 0;
}

}
