#include "X_timeEditDelegate.h"
/*
    delegate.cpp

    A delegate that allows the user to change integer values from the model
    using a spin box widget.
*/

#include "X_timeEditDelegate.h"

#include <QTimeEdit>

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

QWidget *X_timeEditDelegate::createEditor(QWidget *parent,
    const QStyleOptionViewItem &/* option */,
    const QModelIndex & index ) const
{
    if(index.column()==1||index.column()==2)
    {
        QTimeEdit *editor = new QTimeEdit(parent);
        editor->setFrame(false);

        editor->setAlignment(Qt::AlignHCenter);
        editor->setDisplayFormat("hh:mm");

        return editor;

    }
    return nullptr;
}

void X_timeEditDelegate::setEditorData(QWidget *editor,
                                    const QModelIndex &index) const
{
    QString value = index.model()->data(index, Qt::EditRole).toString();

    QTimeEdit *spinBoxTimeEdit = static_cast<QTimeEdit*>(editor);
    QTime qtime=QTime::fromString(value,"hh:mm");
    spinBoxTimeEdit->setTime(qtime);

}

void X_timeEditDelegate::setModelData(QWidget *editor, QAbstractItemModel *model,
                                   const QModelIndex &index) const
{
    QTimeEdit *spinBoxTimeEdit = static_cast<QTimeEdit*>(editor);
    spinBoxTimeEdit->interpretText();
    QString value = spinBoxTimeEdit->time().toString("hh:mm");

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

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

