/**
 ******************************************************************************
 *
 * @file       doublespindelegate.cpp
 * @author     The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010.
 * @addtogroup GCSPlugins GCS Plugins
 * @{
 * @addtogroup ConfigPlugin Config Plugin
 * @{
 * @brief A double spinbox delegate
 *****************************************************************************/
/*
 * 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, write to the Free Software Foundation, Inc.,
 * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 */

#include "dblspindelegate.h"

/**
   Helper delegate for the custom mixer editor table.
 */
DoubleSpinDelegate::DoubleSpinDelegate(QObject *parent)
    : QItemDelegate(parent)
{
    m_min      = 0.0;
    m_max      = 1.0;
    m_decimals = 2;
    m_step     = 0.01;
}

QWidget *DoubleSpinDelegate::createEditor(QWidget *parent,
                                          const QStyleOptionViewItem & /* option */,
                                          const QModelIndex & /* index */) const
{
    QDoubleSpinBox *editor = new QDoubleSpinBox(parent);

    editor->setMinimum(m_min);
    editor->setMaximum(m_max);
    editor->setDecimals(m_decimals);
    editor->setSingleStep(m_step);

    connect(editor, SIGNAL(valueChanged(double)), this, SLOT(valueChanged()));

    return editor;
}

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

    QDoubleSpinBox *spinBox = static_cast<QDoubleSpinBox *>(editor);

    spinBox->setValue(value);
}

void DoubleSpinDelegate::setModelData(QWidget *editor, QAbstractItemModel *model,
                                      const QModelIndex &index) const
{
    QDoubleSpinBox *spinBox = static_cast<QDoubleSpinBox *>(editor);

    spinBox->interpretText();
    double value = spinBox->value();

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

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

void DoubleSpinDelegate::valueChanged()
{
    emit ValueChanged();
}
