/*
 * Copyright (C) 2014-2022 CZ.NIC
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 * In addition, as a special exception, the copyright holders give
 * permission to link the code of portions of this program with the
 * OpenSSL library under certain conditions as described in each
 * individual source file, and distribute linked combinations including
 * the two.
 */

#include <QComboBox>

#include "src/delegates/combobox_delegate.h"
#include "src/models/data_box_contacts_model.h"

ComboBoxItemDelegate::ComboBoxItemDelegate(QObject *parent)
    : QStyledItemDelegate(parent)
{
}

QWidget *ComboBoxItemDelegate::createEditor(QWidget *parent,
    const QStyleOptionViewItem &option, const QModelIndex &index) const
{
	Q_UNUSED(option)

	QComboBox *cb = new (::std::nothrow) QComboBox(parent);
	if (Q_UNLIKELY(cb == Q_NULLPTR)) {
		return Q_NULLPTR;
	}

	connect(cb, SIGNAL(currentIndexChanged(int)),
	    this, SLOT(onCurrentIndexChanged()));

	const QVariant vLsit = index.sibling(index.row(),
	    BoxContactsModel::PAYMENTS_COL).data();
	int idx = 0;
	foreach (const QVariant &v, vLsit.toList()) {
		/* The value of v can be read by currentData(). */
		cb->addItem(BoxContactsModel::descrDmType(v.toInt()), v);
		/* Also set a tooltip. */
		cb->setItemData(idx,
		    BoxContactsModel::dmTypeToolTipDescr(v.toInt()),
		    Qt::ToolTipRole);
		++idx;
	}
	return cb;
}

void ComboBoxItemDelegate::setEditorData(QWidget *editor,
    const QModelIndex &index) const
{
	QComboBox *cb = qobject_cast<QComboBox *>(editor);
	if (Q_UNLIKELY(cb == Q_NULLPTR)) {
		Q_ASSERT(0);
		return;
	}

	const int value = index.model()->data(index, Qt::EditRole).toInt();
	const int cbIndex = cb->findData(value);

	if (cbIndex >= 0) {
		cb->setCurrentIndex(cbIndex);
	}
}

void ComboBoxItemDelegate::setModelData(QWidget *editor,
    QAbstractItemModel *model, const QModelIndex &index) const
{
	const QComboBox *cb = qobject_cast<QComboBox *>(editor);
	if (Q_UNLIKELY(cb == Q_NULLPTR)) {
		Q_ASSERT(0);
		return;
	}
	if (Q_UNLIKELY(model == Q_NULLPTR)) {
		Q_ASSERT(0);
		return;
	}

	model->setData(index, cb->currentData(), Qt::EditRole);
}

void ComboBoxItemDelegate::onCurrentIndexChanged(void)
{
	QComboBox *cb = qobject_cast<QComboBox*>(sender());
	if (Q_UNLIKELY(cb == Q_NULLPTR)) {
		Q_ASSERT(0);
		return;
	}
	emit commitData(cb);
}
