#ifndef FORMBINDER_H
#define FORMBINDER_H

#include <QSharedPointer>
#include <QComboBox>
#include <QWidget>
#include <QMetaMethod>
#include <QMetaProperty>
#include <QVariant>

#include "combodata.h"
#include "ivalidator.h"
#include "iform.h"

#include "../qdecimal/src/QDecDouble.hh"

template<class T>
class FormBinder : public IForm
{
public:

    explicit FormBinder(QWidget *parent = NULL) : IForm(parent) {}

    virtual ~FormBinder() {
        foreach (IValidator *val, m_validators) {
            delete val;
        }
        m_validators.clear();
    }

    void registerBinding(QWidget *widget) {
        if (!m_bindWidgets.contains(widget)) {
            m_bindWidgets.append(widget);
        }
    }

    void registerBinding(QComboBox *combo, const QList<ComboData> &values) {
        m_bindCombos[combo] = values;
    }

    void registerValidator(IValidator *validator) {
        m_validators.append(validator);
    }

    void setEntity(QSharedPointer<T> entity) {
        m_entity = entity;
        bindToUi();
    }

    QSharedPointer<T> entity() {
        return m_entity;
    }

protected:
    QSharedPointer<T> m_entity;

    virtual void bindOtherToUi() {}
    virtual bool bindOtherToData() { return true; }
    virtual void registerCombos() {}

    void bindToUi() {
        registerCombos();
        foreach (QWidget *widget, m_bindWidgets) {
            const char* prop = widget->metaObject()->userProperty().name();
            QVariant value = ((QObject*)m_entity.data())->property(widget->objectName().toStdString().c_str());
            if (value.canConvert<QDecDouble>())
            {
                widget->setProperty(prop, value.value<QDecDouble>().toString());
            }
            else
            {
                widget->setProperty(prop, value);
            }
        }

        foreach (QComboBox *combo, m_bindCombos.keys()) {
            int idx = 0;
            QVariant field = ((QObject*)m_entity.data())->property(combo->objectName().toStdString().c_str());

            combo->clear();
            for (int i = 0; i < m_bindCombos[combo].size(); i++) {
                ComboData data = m_bindCombos[combo][i];
                combo->addItem(data.label(), data.index());

                if (data.index().canConvert<QObject*>()) {
                    ComboItem* ci = qobject_cast<ComboItem*>(data.index().value<QObject*>());
                    ComboItem* ciField = qobject_cast<ComboItem*>(field.value<QObject*>());
                    if (ci->eq(ciField)) {
                        idx = i;
                    }
                }
                else if (field == data.index()) {
                    idx = i;
                }
            }

            combo->setCurrentIndex(idx);
        }

        bindOtherToUi();
    }

    bool bindToData() {
        foreach (IValidator *val, m_validators) {
            if (!val->validate()) {
                emit validationError(val->errMessage());
                return false;
            }
        }

        foreach (QWidget *widget, m_bindWidgets) {
            const char* prop = widget->metaObject()->userProperty().name();

            QVariant val = widget->property(prop);
            if (((QObject*)m_entity.data())->property(widget->objectName().toStdString().c_str()).canConvert<QDecDouble>())
            {
                QDecDouble dec(val.toDouble());
                val = QVariant::fromValue(dec);
            }
            ((QObject*)m_entity.data())->setProperty(widget->objectName().toStdString().c_str(), val);
        }

        foreach (QComboBox *combo, m_bindCombos.keys()) {
            ((QObject*)m_entity.data())->setProperty(combo->objectName().toStdString().c_str(), combo->currentData());
        }

        return bindOtherToData();
    }

private:
    QList<QWidget*> m_bindWidgets;
    QHash<QComboBox*, QList<ComboData> > m_bindCombos;
    QList<IValidator*> m_validators;
};

#endif // FORMBINDER_H
