#include "CheckComboBoxWidget.h"

#include <QAbstractItemView>
#include <QMouseEvent>
#include <QLineEdit>

const QString CheckComboBoxWidget::type = "CheckComboBox";

CheckComboBoxWidget::CheckComboBoxWidget(QWidget *parent)
    :ComboBoxWidget(parent)
{
    view()->viewport()->installEventFilter(this);
    setEditable(true);
}

QVariant CheckComboBoxWidget::getValue() const
{
    return dictValues.join(_delimiter);
}

void CheckComboBoxWidget::setValue(const QVariant& value)
{
    foreach(auto & var, value.toList())
    {
        dictValues << var.toString();
    }
    lineEdit()->setText(dictValues.join(_delimiter));
}

bool CheckComboBoxWidget::isValueNull() const
{
    return dictValues.size();
}

void CheckComboBoxWidget::clearInput()
{
    dictValues.clear();
    lineEdit()->clear();
    for (int i = 0; i < count(); i++)
    {
        setItemData(i,false,Qt::CheckStateRole);
    }
}


bool CheckComboBoxWidget::eventFilter(QObject * watched, QEvent * event)
{
    if (event->type() == QEvent::MouseButtonRelease)
    {
        QModelIndex ind = view()->indexAt(((QMouseEvent*)event)->pos());
        bool checked = view()->model()->data(ind, Qt::CheckStateRole).toBool();
        view()->model()->setData(ind, !checked, Qt::CheckStateRole);
        return true;
    }
    return QObject::eventFilter(watched, event);
}

void CheckComboBoxWidget::hidePopup()
{
    QStringList values;
    dictValues.clear();
    for (int i = 0; i < count(); i++)
    {
        if (itemData(i, Qt::CheckStateRole).toBool())
        {
            values << itemText(i);
            dictValues << itemData(i).toString();
            setCurrentIndex(i);
        }
    }
    setCurrentText(values.join(_delimiter));
    emit selectedText(values);
    QComboBox::hidePopup();
}

void CheckComboBoxWidget::showPopup()
{
    QStringList values = currentText().split(_delimiter);

    for (int i = 1; i<count(); i++)
    {
        setItemData(i, values.contains(itemText(i)), Qt::CheckStateRole);
    }
    QComboBox::showPopup();
}

