#include "ComboBoxWidgetFactory.h"
#include "ComboBoxWidget.h"

ComboBoxWidgetFactory::ComboBoxWidgetFactory()
{

}


void ComboBoxWidgetFactory::create(qx::IxDataMember *dataMember, QWidget *parent)
{
    widget = new ComboBoxWidget(parent);
    QVariantMap options;
    if (dataMember->getPropertyBag("dict").isValid())
    {
        options = dataMember->getPropertyBag("dict").toMap();
    }
    else
    {
        QString param = dataMember->getPropertyBag("param").toString();
        qx::any any = invokeStatic(dataMember, dataMember->getName() + "Options", param);
        if (any.empty())
            return;
        options = qx::any_cast<QVariantMap>(any);
    }
    widget->setOptions(options);
    if (dataMember->getPropertyBag("cascade").isValid())
    {
        QString fieldName = dataMember->getPropertyBag("cascade").toString();
        using func = void (QComboBox::*)(int);
        ComboBoxWidget *mainWidget = widget;
        QObject::connect(widget, static_cast<func>(&QComboBox::currentIndexChanged), [this,dataMember, parent, fieldName,mainWidget](){

            ComboBoxWidget *cascadeWidget = parent->findChild<ComboBoxWidget*>(fieldName);
            if (!cascadeWidget)
                return;
            QString param = mainWidget->getValue().toString();

            qx::any any = invokeStatic(dataMember, "cascadeMethod", param);
            if (any.empty())
                return;
            QVariantMap cascadeOptions = qx::any_cast<QVariantMap>(any);
            if (cascadeOptions.size() > 0)
                cascadeWidget->setOptions(cascadeOptions);
        });
    }
}

QString ComboBoxWidgetFactory::type() const
{
    return ComboBoxWidget::type;
}

QWidget *ComboBoxWidgetFactory::getWidget() const
{
     return widget;
}

IxWidget *ComboBoxWidgetFactory::getIxWidget() const
{
     return widget;
}
