#include "itemcomboboxdelegate.h"

#include <QComboBox>
#include <QTableView>
#include <QHeaderView>

ItemComboboxDelegate::ItemComboboxDelegate(QObject *parent) :
    QItemDelegate(parent)
{

}

QWidget *ItemComboboxDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    QComboBox *editor = new QComboBox(parent);
    editor->installEventFilter(const_cast<ItemComboboxDelegate *>(this));

    QTableView* tableView = new QTableView();
    QHeaderView* header=tableView->verticalHeader();
    header->setDefaultSectionSize(20); // 20 px height
    header->sectionResizeMode(QHeaderView::Fixed);
    //tableView->setModel( unitModel );
    tableView->verticalHeader()->setVisible(false);
    tableView->horizontalHeader()->setVisible(false);
    tableView->setColumnWidth ( 0, 60 );
    tableView->setColumnWidth ( 1, 160 );
    tableView->setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded);
    tableView->setSelectionBehavior(QAbstractItemView::SelectRows);
    tableView->setAutoScroll(false);
    //ui->comboUnit->setModel( unitModel );
    editor->setView( tableView );
    editor->view()->setMinimumWidth(220);


    return editor;
}

void ItemComboboxDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const
{
    QString value = index.model()->data(index, Qt::EditRole).toString();
    QComboBox *dsb = static_cast<QComboBox*>(editor);
    dsb->setCurrentText(value);
}

void ItemComboboxDelegate::setModelData(QWidget *editor, QAbstractItemModel *model,
                                 const QModelIndex& index) const
{
    QComboBox *dsb = static_cast<QComboBox*>(editor);
    //dsb->interpretText();
    //double value = dsb->value();
    model->setData(index, dsb->currentText(), Qt::EditRole);
}

void ItemComboboxDelegate::updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option,
                                         const QModelIndex& /* index */) const
{
    editor->setGeometry(option.rect);
}
