#include "SelectionEditorFactory.h"
#include "AbstractModelFactory.h"
#include <QComboBox>

SelectionEditorFactory::SelectionEditorFactory(QObject *parent, AbstractModelFactory *model_factory, int key_column, int value_column)
	: AbstractEditorFactory(parent)
	, m_modelFactory(model_factory)
	, m_keyColumn(key_column)
	, m_valueColumn(value_column)
{}

QWidget *SelectionEditorFactory::createEditor (QWidget *parent, const QStyleOptionViewItem &,
							   const QModelIndex &) const
{
	QWidget *w = nullptr;

	QComboBox *cmbbx = new QComboBox(parent);
	cmbbx->setMaxVisibleItems(32);
	auto model = m_modelFactory->createModel(cmbbx);
	cmbbx->setModel(model);
	cmbbx->setModelColumn(m_valueColumn);
	w = cmbbx;

	return w;
}

void SelectionEditorFactory::setEditorData(QWidget *editor, const QModelIndex &index) const
{
	QComboBox *cmbbx = dynamic_cast<QComboBox*>(editor);
	if (cmbbx) {
		auto data = index.data(Qt::EditRole);

		auto list_model = cmbbx->model();
		QModelIndexList indexes = list_model->match(
				list_model->index(0, m_keyColumn), Qt::DisplayRole, data, 1, Qt::MatchFlags( Qt::MatchExactly ));
		if (!indexes.empty()) {
			cmbbx->setCurrentIndex(indexes.at(0).row());
		}
		else {
			cmbbx->setCurrentIndex(-1);
		}
	}
}

void SelectionEditorFactory::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const
{
	QComboBox *cmbbx = dynamic_cast<QComboBox*>(editor);
	if (cmbbx) {
		auto data = index.data();
		if (data.canConvert<QString>()) {
			auto list_model = cmbbx->model();
			QVariant d = list_model->data(
						list_model->index(cmbbx->currentIndex(), m_keyColumn));
			model->setData(index, d);
		}
	}
}

