/***************************************************************************
 *   Copyright (C) 2008 by S. MANKOWSKI / G. DE BURE support@mankowski.fr  *
 *                                                                         *
 *   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 2 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, see <http://www.gnu.org/licenses/>  *
 ***************************************************************************/
/** @file
 * This file is a query creator for skrooge
 *
 * @author Stephane MANKOWSKI / Guillaume DE BURE
 */
#include "skgpredicatcreator.h"

#include <qdom.h>
#include <qtablewidget.h>
#include <qcheckbox.h>
#include <qapplication.h>
#include <qlineedit.h>

#include "skgdocument.h"
#include "skgmainpanel.h"
#include "skgservices.h"
#include "skgcombobox.h"
#include "skgcalculatoredit.h"
#include "skgdateedit.h"
#include "skgruleobject.h"

SKGPredicatCreator::SKGPredicatCreator(QWidget* iParent, SKGDocument* document, const QString& attribute, bool iModeUpdate, const QStringList& iListAtt)
    : QWidget(iParent), m_updateMode(iModeUpdate), m_kValue1(nullptr), m_kValue2(nullptr), m_kAttributes(nullptr)
{
    SKGServices::AttributeType attType = SKGServices::TEXT;
    if (document) {
        attType = document->getAttributeType(attribute);
    }

    // Build
    this->setAutoFillBackground(true);
    this->resize(491, 25);
    auto horizontalLayout = new QHBoxLayout(this);
    horizontalLayout->setSpacing(2);
    horizontalLayout->setMargin(0);
    horizontalLayout->setObjectName(QStringLiteral("horizontalLayout"));
    m_kOperator = new SKGComboBox(this);
    m_kOperator->setObjectName(QStringLiteral("kOperator"));
    m_kOperator->setSizeAdjustPolicy(KComboBox::AdjustToContentsOnFirstShow);
    QSizePolicy newSizePolicy2(QSizePolicy::Fixed, QSizePolicy::Fixed);
    newSizePolicy2.setHorizontalStretch(0);
    newSizePolicy2.setVerticalStretch(0);
    newSizePolicy2.setHeightForWidth(m_kOperator->sizePolicy().hasHeightForWidth());
    m_kOperator->setSizePolicy(newSizePolicy2);

    horizontalLayout->addWidget(m_kOperator);
    int nbAtt = iListAtt.count();
    if (nbAtt) {
        m_kAttributes = new SKGComboBox(this);
        if (m_kAttributes) {
            m_kAttributes->setObjectName(QStringLiteral("kAttributes"));
            m_kAttributes->setMinimumSize(QSize(100, 0));
            m_kAttributes->setEditable(false);
            QSizePolicy newSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
            newSizePolicy.setHorizontalStretch(0);
            newSizePolicy.setVerticalStretch(0);
            newSizePolicy.setHeightForWidth(m_kAttributes->sizePolicy().hasHeightForWidth());
            m_kAttributes->setSizePolicy(newSizePolicy);

            horizontalLayout->addWidget(m_kAttributes);

            for (const auto& att : qAsConst(iListAtt)) {
                if (document) {
                    m_kAttributes->addItem(document->getIcon(att), document->getDisplay(att), att);
                }
            }
        }
    }
    if (attType == SKGServices::TEXT) {
        auto cmbVal1 = new SKGComboBox(this);
        if (cmbVal1) {
            cmbVal1->setObjectName(QStringLiteral("cmbVal1"));
            cmbVal1->setMinimumSize(QSize(100, 0));
            cmbVal1->setEditable(true);
            QSizePolicy newSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
            newSizePolicy.setHorizontalStretch(0);
            newSizePolicy.setVerticalStretch(0);
            newSizePolicy.setHeightForWidth(cmbVal1->sizePolicy().hasHeightForWidth());
            cmbVal1->setSizePolicy(newSizePolicy);
            cmbVal1->lineEdit()->setPlaceholderText(i18n("Value"));

            horizontalLayout->addWidget(cmbVal1);
            m_kValue1 = cmbVal1;
        }
        auto cmbVal2 = new SKGComboBox(this);
        if (cmbVal2) {
            cmbVal2->setObjectName(QStringLiteral("cmbVal2"));
            cmbVal2->setMinimumSize(QSize(100, 0));
            cmbVal2->setEditable(true);
            QSizePolicy newSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
            newSizePolicy.setHorizontalStretch(0);
            newSizePolicy.setVerticalStretch(0);
            newSizePolicy.setHeightForWidth(cmbVal2->sizePolicy().hasHeightForWidth());
            cmbVal2->setSizePolicy(newSizePolicy);
            cmbVal2->lineEdit()->setPlaceholderText(i18n("Value"));

            horizontalLayout->addWidget(cmbVal2);
            m_kValue2 = cmbVal2;
        }

        if (document) {
            QString realTable = QStringLiteral("operation");
            QString realAtt = attribute;
            QString realCond = QStringLiteral("");
            if (attribute == QStringLiteral("t_REALCATEGORY")) {
                realTable = QStringLiteral("category");
                realAtt = QStringLiteral("t_fullname");
            } else if (attribute == QStringLiteral("t_BANK")) {
                realTable = QStringLiteral("bank");
                realAtt = QStringLiteral("t_name");
            } else if (attribute == QStringLiteral("t_ACCOUNT") || attribute == QStringLiteral("t_TOACCOUNT")) {
                realTable = QStringLiteral("account");
                realAtt = QStringLiteral("t_name");
            } else if (attribute == QStringLiteral("t_UNIT")) {
                realTable = QStringLiteral("unit");
                realAtt = QStringLiteral("t_name");
            } else if (attribute == QStringLiteral("t_REALCOMMENT")) {
                realTable = QStringLiteral("suboperation");
                realAtt = QStringLiteral("t_comment");
            } else if (attribute == QStringLiteral("t_REALREFUND")) {
                realTable = QStringLiteral("refund");
                realAtt = QStringLiteral("t_name");
            } else if (attribute == QStringLiteral("t_PAYEE")) {
                realTable = QStringLiteral("payee");
                realAtt = QStringLiteral("t_name");
            } else if (attribute.startsWith(QLatin1String("p_"))) {
                realTable = QStringLiteral("parameters");
                realAtt = QStringLiteral("t_value");
                realCond = "t_name='" % attribute.right(attribute.length() - 2) % '\'';
            }
            SKGMainPanel::fillWithDistinctValue(QList<QWidget*>() << cmbVal1 << cmbVal2, document, realTable, realAtt, realCond);
        }
    } else  if (attType == SKGServices::INTEGER || attType == SKGServices::FLOAT) {
        auto cmbVal1 = new SKGCalculatorEdit(this);
        if (cmbVal1) {
            cmbVal1->setObjectName(QStringLiteral("cmbVal1"));
            cmbVal1->setMode(SKGCalculatorEdit::EXPRESSION);
            cmbVal1->setMinimumSize(QSize(100, 0));

            horizontalLayout->addWidget(cmbVal1);
            m_kValue1 = cmbVal1;
        }
        auto cmbVal2 = new SKGCalculatorEdit(this);
        if (cmbVal2) {
            cmbVal2->setObjectName(QStringLiteral("cmbVal2"));
            cmbVal2->setMode(SKGCalculatorEdit::EXPRESSION);
            cmbVal2->setMinimumSize(QSize(100, 0));

            horizontalLayout->addWidget(cmbVal2);
            m_kValue2 = cmbVal2;
        }
    } else  if (attType == SKGServices::DATE) {
        if (iModeUpdate) {
            auto cmbVal1 = new SKGComboBox(this);
            if (cmbVal1) {
                cmbVal1->setObjectName(QStringLiteral("cmbVal1"));
                cmbVal1->setMinimumSize(QSize(100, 0));
                cmbVal1->setEditable(true);
                QSizePolicy newSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
                newSizePolicy.setHorizontalStretch(0);
                newSizePolicy.setVerticalStretch(0);
                newSizePolicy.setHeightForWidth(cmbVal1->sizePolicy().hasHeightForWidth());
                cmbVal1->setSizePolicy(newSizePolicy);
                cmbVal1->lineEdit()->setPlaceholderText(i18n("Value"));

                horizontalLayout->addWidget(cmbVal1);
                m_kValue1 = cmbVal1;
            }

            auto cmbVal2 = new SKGComboBox(this);
            if (cmbVal2) {
                cmbVal2->setObjectName(QStringLiteral("cmbVal2"));
                cmbVal2->setMinimumSize(QSize(100, 0));
                cmbVal2->setEditable(false);
                QSizePolicy newSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
                newSizePolicy.setHorizontalStretch(0);
                newSizePolicy.setVerticalStretch(0);
                newSizePolicy.setHeightForWidth(cmbVal2->sizePolicy().hasHeightForWidth());
                cmbVal2->setSizePolicy(newSizePolicy);
                cmbVal2->addItems(QStringList() << QStringLiteral("YYYYMMDD") << QStringLiteral("MMDDYYYY") << QStringLiteral("DDMMYYYY")
                                  << QStringLiteral("MM-DD-YY") << QStringLiteral("DD-MM-YY") << QStringLiteral("MM-DD-YYYY") << QStringLiteral("DD-MM-YYYY") << QStringLiteral("YYYY-MM-DD"));
                horizontalLayout->addWidget(cmbVal2);
                m_kValue2 = cmbVal2;
            }
        } else {
            auto cmbVal1 = new SKGDateEdit(this);
            if (cmbVal1) {
                cmbVal1->setObjectName(QStringLiteral("cmbVal1"));
                cmbVal1->setMinimumSize(QSize(100, 0));

                horizontalLayout->addWidget(cmbVal1);
                m_kValue1 = cmbVal1;
            }

            auto cmbVal2 = new SKGDateEdit(this);
            if (cmbVal2) {
                cmbVal2->setObjectName(QStringLiteral("cmbVal2"));
                cmbVal2->setMinimumSize(QSize(100, 0));

                horizontalLayout->addWidget(cmbVal2);
                m_kValue2 = cmbVal2;
            }
        }
    } else  if (attType == SKGServices::BOOL || attType == SKGServices::TRISTATE) {
        auto cmbVal1 = new QCheckBox(this);
        if (cmbVal1) {
            cmbVal1->setObjectName(QStringLiteral("cmbVal1"));
            cmbVal1->setMinimumSize(QSize(100, 0));
            cmbVal1->setTristate(attType == SKGServices::TRISTATE);

            horizontalLayout->addWidget(cmbVal1);
            m_kValue1 = cmbVal1;
        }
    }

    // Fill combo boxes
    m_kOperator->clear();
    m_kOperator->addItem(QStringLiteral(""), "");

    if (m_kValue1) {
        m_kValue1->installEventFilter(this);
    }
    if (m_kValue2) {
        m_kValue2->installEventFilter(this);
    }
    if (m_kOperator) {
        m_kOperator->installEventFilter(this);
    }
    if (m_kAttributes) {
        m_kAttributes->installEventFilter(this);
    }

    QStringList listOps = SKGRuleObject::getListOfOperators(attType, m_updateMode ? SKGRuleObject::UPDATE : SKGRuleObject::SEARCH);
    int nb = listOps.count();
    if (iModeUpdate && attribute == QStringLiteral("t_REALCATEGORY") && nb > 1) {
        nb = 1;    // TODO(Stephane MANKOWSKI): unblock t_REALCATEGORY
    }
    for (int i = 0; i < nb; ++i) {
        QString op = listOps.at(i);
        QString nlsOp = SKGRuleObject::getDisplayForOperator(op,
                        i18nc("Default value", "..."),
                        i18nc("Default value", "..."),
                        i18nc("Noun, an item's attribute", "attribute"));
        if (m_kOperator) {
            m_kOperator->addItem(nlsOp, op);
        }
    }

    connect(m_kOperator, static_cast<void (SKGComboBox::*)(const QString&)>(&SKGComboBox::currentIndexChanged), this, &SKGPredicatCreator::onOperatorChanged);
    onOperatorChanged();
}

SKGPredicatCreator::~SKGPredicatCreator()
{
    m_kOperator = nullptr;
    m_kValue1 = nullptr;
    m_kValue2 = nullptr;
    m_kAttributes = nullptr;
}

bool SKGPredicatCreator::eventFilter(QObject* iObject, QEvent* iEvent)
{
    Q_UNUSED(iObject);
    if (iEvent && (iEvent->type() == QEvent::FocusIn || iEvent->type() == QEvent::FocusOut)) {
        QObject* appliFocus = QApplication::focusWidget();

        while (appliFocus) {
            if (appliFocus == this) {
                break;
            }
            appliFocus = appliFocus->parent();
        }
        if (!appliFocus) {
            Q_EMIT editingFinished();
        }
    }
    return false;
}

void SKGPredicatCreator::onOperatorChanged()
{
    QString req;
    if (m_kOperator) {
        req = m_kOperator->itemData(m_kOperator->currentIndex()).toString();

        m_kOperator->setToolTip(SKGRuleObject::getToolTipForOperator(req));
    }
    if (m_kValue1) {
        m_kValue1->setVisible(req.contains(QStringLiteral("#V1S#")) || req.contains(QStringLiteral("#V1#")));
    }
    if (m_kValue2) {
        m_kValue2->setVisible(req.contains(QStringLiteral("#V2S#")) || req.contains(QStringLiteral("#V2#")) || req.contains(QStringLiteral("#DF#")));
    }
    if (m_kAttributes) {
        m_kAttributes->setVisible(req.contains(QStringLiteral("#ATT2#")));
    }
}

QString SKGPredicatCreator::text()
{
    return SKGPredicatCreator::getTextFromXml(xmlDescription());
}

QString SKGPredicatCreator::getTextFromXml(const QString& iXML)
{
    QDomDocument doc(QStringLiteral("SKGML"));
    doc.setContent(iXML);
    QDomElement root = doc.documentElement();
    QString output = SKGRuleObject::getDisplayForOperator(root.attribute(QStringLiteral("operator")),
                     root.attribute(QStringLiteral("value")),
                     root.attribute(QStringLiteral("value2")),
                     root.attribute(QStringLiteral("att2s")));
    return output;
}

QString SKGPredicatCreator::xmlDescription()
{
    QString output;
    if (m_kOperator) {
        QString op = m_kOperator->itemData(m_kOperator->currentIndex()).toString();
        if (!op.isEmpty()) {
            QDomDocument doc(QStringLiteral("SKGML"));
            QDomElement root = doc.createElement(QStringLiteral("element"));
            doc.appendChild(root);

            // Condition
            root.setAttribute(QStringLiteral("operator"), op);
            if (m_kValue1 && m_kValue1->isVisible()) {
                SKGDateEdit* cmbVal1 = qobject_cast<SKGDateEdit*> (m_kValue1);
                if (cmbVal1) {
                    root.setAttribute(QStringLiteral("value"), SKGServices::dateToSqlString(QDateTime(cmbVal1->date())));
                } else {
                    SKGCalculatorEdit* cmbVal12 = qobject_cast<SKGCalculatorEdit*> (m_kValue1);
                    if (cmbVal12) {
                        root.setAttribute(QStringLiteral("value"), cmbVal12->text());
                    } else {
                        QCheckBox* cmbVal13 = qobject_cast<QCheckBox*> (m_kValue1);
                        if (cmbVal13) {
                            root.setAttribute(QStringLiteral("value"), cmbVal13->checkState() == Qt::Checked ? QStringLiteral("Y") : cmbVal13->checkState() == Qt::Unchecked ? QStringLiteral("N") : QStringLiteral("P"));
                        } else {
                            SKGComboBox* cmbVal14 = qobject_cast<SKGComboBox*> (m_kValue1);
                            if (cmbVal14) {
                                root.setAttribute(QStringLiteral("value"), cmbVal14->text());
                            }
                        }
                    }
                }
            }
            if (m_kValue2 && m_kValue2->isVisible()) {
                SKGDateEdit* cmbVal2 = qobject_cast<SKGDateEdit*> (m_kValue2);
                if (cmbVal2) {
                    root.setAttribute(QStringLiteral("value2"), SKGServices::dateToSqlString(QDateTime(cmbVal2->date())));
                } else {
                    SKGCalculatorEdit* cmbVal21 = qobject_cast<SKGCalculatorEdit*> (m_kValue2);
                    if (cmbVal21) {
                        root.setAttribute(QStringLiteral("value2"), cmbVal21->text());
                    } else {
                        SKGComboBox* cmbVal22 = qobject_cast<SKGComboBox*> (m_kValue2);
                        if (cmbVal22) {
                            root.setAttribute(QStringLiteral("value2"), cmbVal22->text());
                        }
                    }
                }
            }

            if (m_kAttributes && m_kAttributes->isVisible()) {
                root.setAttribute(QStringLiteral("att2"), m_kAttributes->itemData(m_kAttributes->currentIndex()).toString());
                root.setAttribute(QStringLiteral("att2s"), m_kAttributes->text());
            }

            output = doc.toString();
        }
    }
    return output;
}

void SKGPredicatCreator::setXmlDescription(const QString& iXML)
{
    QDomDocument doc(QStringLiteral("SKGML"));
    doc.setContent(iXML);
    QDomElement root = doc.documentElement();

    // Condition
    if (m_kOperator) {
        m_kOperator->setCurrentIndex(m_kOperator->findData(root.attribute(QStringLiteral("operator"))));
        SKGDateEdit* cmbVal1 = qobject_cast<SKGDateEdit*> (m_kValue1);
        if (cmbVal1) {
            cmbVal1->setDate(SKGServices::stringToTime(root.attribute(QStringLiteral("value"))).date());
        } else {
            SKGCalculatorEdit* cmbVal12 = qobject_cast<SKGCalculatorEdit*> (m_kValue1);
            if (cmbVal12) {
                cmbVal12->setText(root.attribute(QStringLiteral("value")));
            } else {
                QCheckBox* cmbVal13 = qobject_cast<QCheckBox*> (m_kValue1);
                if (cmbVal13) {
                    cmbVal13->setCheckState(root.attribute(QStringLiteral("value")) == QStringLiteral("Y") ? Qt::Checked : root.attribute(QStringLiteral("value")) == QStringLiteral("P") ? Qt::PartiallyChecked : Qt::Unchecked);
                } else {
                    SKGComboBox* cmbVal14 = qobject_cast<SKGComboBox*> (m_kValue1);
                    if (cmbVal14) {
                        cmbVal14->setText(root.attribute(QStringLiteral("value")));
                    }
                }
            }
        }

        SKGDateEdit* cmbVal2 = qobject_cast<SKGDateEdit*> (m_kValue2);
        if (cmbVal2) {
            cmbVal2->setDate(SKGServices::stringToTime(root.attribute(QStringLiteral("value2"))).date());
        } else {
            SKGCalculatorEdit* cmbVal22 = qobject_cast<SKGCalculatorEdit*> (m_kValue2);
            if (cmbVal22) {
                cmbVal22->setText(root.attribute(QStringLiteral("value2")));
            } else {
                SKGComboBox* cmbVal23 = qobject_cast<SKGComboBox*> (m_kValue2);
                if (cmbVal23) {
                    cmbVal23->setText(root.attribute(QStringLiteral("value2")));
                }
            }
        }

        if (m_kAttributes) {
            m_kAttributes->setCurrentIndex(m_kAttributes->findData(root.attribute(QStringLiteral("att2"))));
        }
    }
}



