#include "itemtextpopupdelegate.h"
#include "mlineeditbutton.h"

#include <QDebug>

ItemTextPopupDelegate::ItemTextPopupDelegate(QObject *parent) :
    QItemDelegate(parent),
    mInitialValue("")
{

}

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

void ItemTextPopupDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const
{
    QString value = index.data().toString();
    MLineEditButton *dsb = static_cast<MLineEditButton*>(editor);
    dsb->setText(value);

    // save initial value:
    ItemTextPopupDelegate *ptr = const_cast<ItemTextPopupDelegate*>(this);
    ptr->mInitialValue = value;
}

void ItemTextPopupDelegate::setModelData(QWidget *editor, QAbstractItemModel *model,
                                 const QModelIndex& index) const
{
    MLineEditButton *dsb = static_cast<MLineEditButton*>(editor);
    qDebug() << dsb->text();
    if(mInitialValue != dsb->text())
        model->setData(index, dsb->text(), Qt::EditRole);
}

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