/***************************************************************************
 *   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
 * A skrooge plugin to search and process operations.
 *
 * @author Stephane MANKOWSKI
 */
#include "skgsearchpluginwidget.h"

#include <KStandardDirs>

#include <QDomDocument>
#include <QDir>
#include <QKeyEvent>

#include "skgobjectmodel.h"
#include "skgmainpanel.h"
#include "skgtraces.h"
#include "skgdocument.h"
#include "skgbankincludes.h"
#include "skgservices.h"
#include "skgcategoryobject.h"
#include "skgruleobject.h"

SKGSearchPluginWidget::SKGSearchPluginWidget(SKGDocument* iDocument)
    : SKGTabPage(iDocument)
{
    SKGTRACEINFUNC(1);
    if (!iDocument) {
        return;
    }

    ui.setupUi(this);

    ui.kView->getShowWidget()->addItem("search", i18nc("Noun, a search", "Search"), "edit-find", "t_action_type='S'", "", "", "", "", Qt::META + Qt::Key_S);
    ui.kView->getShowWidget()->addItem("update", i18nc("Noun, a modification", "Update"), "view-refresh", "t_action_type='U'", "", "", "", "", Qt::META + Qt::Key_U);
    ui.kView->getShowWidget()->addItem("alarm", i18nc("Noun, an alarm", "Alarm"), "dialog-warning", "t_action_type='A'", "", "", "", "", Qt::META + Qt::Key_A);
    ui.kView->getShowWidget()->addItem("template", i18nc("Noun, a modification by applying a template", "Template"), "skrooge_template", "t_action_type='T'", "", "", "", "", Qt::META + Qt::Key_T);
    ui.kView->getShowWidget()->addSeparator();
    ui.kView->getShowWidget()->addItem("highlighted", i18nc("Adjective, an highlighted item", "Highlighted"), "bookmarks", "t_bookmarked='Y'", "", "", "", "", Qt::META + Qt::Key_H);
    ui.kView->getShowWidget()->setDefaultState("search;update;alarm;highlighted");

    // Add Standard KDE Icons to buttons
    ui.kUpdate->setIcon(KIcon("dialog-ok-apply"));
    ui.kAdd->setIcon(KIcon("list-add"));
    ui.kSearch->setIcon(KIcon("edit-find"));
    QStringList overlayopen;
    overlayopen.push_back("skg_open");
    ui.kOpenReport->setIcon(KIcon("view-investment", NULL, overlayopen));

    ui.kTopBtn->setIcon(KIcon("arrow-up-double"));
    ui.kUpBtn->setIcon(KIcon("arrow-up"));
    ui.kDownBtn->setIcon(KIcon("arrow-down"));
    ui.kBottomBtn->setIcon(KIcon("arrow-down-double"));

    {
        SKGWidgetSelector::SKGListQWidget list;
        list.push_back(ui.kQueryGrp);
        list.push_back(ui.kBtnFrm);
        ui.kWidgetSelector->addButton(KIcon("edit-find"), i18n("Search"), i18n("Display the edit panel for searches"), list);
    }
    {
        SKGWidgetSelector::SKGListQWidget list;
        list.push_back(ui.kQueryGrp);
        list.push_back(ui.kBtnFrm);
        list.push_back(ui.kActionGrp);
        ui.kWidgetSelector->addButton(KIcon("view-refresh"), i18n("Update"), i18n("Display the edit panel for updates"), list);
    }
    {
        SKGWidgetSelector::SKGListQWidget list;
        list.push_back(ui.kQueryGrp);
        list.push_back(ui.kBtnFrm);
        list.push_back(ui.kAlarmFrm);
        ui.kWidgetSelector->addButton(KIcon("dialog-warning"), i18n("Alarm"), i18n("Display the edit panel for alarm"), list);
    }
    {
        SKGWidgetSelector::SKGListQWidget list;
        list.push_back(ui.kQueryGrp);
        list.push_back(ui.kBtnFrm);
        list.push_back(ui.kTemplateFrm);
        ui.kWidgetSelector->addButton(KIcon("skrooge_template"), i18n("Template"), i18n("Display the edit panel for updates by templates"), list);
    }

    // Fill combo boxes
    SKGStringListList result;
    iDocument->executeSelectSqliteOrder("SELECT id, t_displayname FROM v_operation_displayname WHERE t_template='Y' ORDER BY t_displayname", result);
    int nb2 = result.count();
    for (int i = 1; i < nb2; ++i) {  // Ignore header
        QStringList r = result.at(i);
        ui.kTemplate->addItem(r.at(1), r.at(0));
    }

    QStringList attributeForQuery;
    attributeForQuery << "d_DATEOP" << "i_number" << "t_mode" << "t_PAYEE" << "t_comment" << "t_REALCOMMENT" << "t_REALCATEGORY" << "t_status" << "t_bookmarked" << "t_imported" << "t_TRANSFER" << "t_UNIT" << "t_ACCOUNT" << "t_TOACCOUNT" << "f_REALCURRENTAMOUNT" << "t_REALREFUND" << "f_BALANCE";
    QStringList attributeForUpdate;
    attributeForUpdate << "d_DATEOP" << "i_number" << "t_mode" << "t_PAYEE" << "t_comment" << "t_status" << "t_bookmarked" << "t_imported" << "t_REALCOMMENT" << "t_REALCATEGORY" << "t_ACCOUNT" << "t_REALREFUND" << "t_UNIT";
    // WARNING: trigger must be modified if this list is modifier

    // Adding properties
    QStringList properties;
    iDocument->getDistinctValues("parameters", "t_name", "t_uuid_parent like '%-operation' AND t_name NOT LIKE 'SKG_%'", properties);
    int nb = properties.count();
    for (int i = 0; i < nb; ++i) {
        attributeForQuery.push_back("p_" % properties.at(i));
        attributeForUpdate.push_back("p_" % properties.at(i));
    }

    ui.kQueryCreator->setParameters(iDocument, "v_suboperation_consolidated", attributeForQuery);
    ui.kActionCreator->setParameters(iDocument, "v_suboperation_consolidated", attributeForUpdate, true);

    // Bind operation view
    ui.kView->setModel(new SKGObjectModel(static_cast<SKGDocumentBank*>(getDocument()), "v_rule_display", "1=1 ORDER BY f_sortorder", this, "", false));
    ui.kView->getView()->sortByColumn(0, Qt::AscendingOrder);

    // Add registered global action in contextual menu
    if (SKGMainPanel::getMainPanel()) {
        ui.kView->getView()->insertGlobalAction();
        ui.kView->getView()->insertGlobalAction("open");
        ui.kView->getView()->insertGlobalAction("open_report");
        ui.kView->getView()->insertGlobalAction();
        ui.kView->getView()->insertGlobalAction("edit_delete");
        ui.kView->getView()->insertGlobalAction();
        ui.kView->getView()->insertGlobalAction("edit_switch_highlight");
        ui.kView->getView()->insertGlobalAction();
        ui.kView->getView()->insertGlobalAction("execute_all");
        ui.kView->getView()->insertGlobalAction("execute_imported");
        ui.kView->getView()->insertGlobalAction("execute_not_validated");

        KMenu* menu = new KMenu(this);
        menu->setIcon(KIcon("system-run"));
        menu->addAction(SKGMainPanel::getMainPanel()->getGlobalAction("execute_all"));
        menu->addAction(SKGMainPanel::getMainPanel()->getGlobalAction("execute_imported"));
        menu->addAction(SKGMainPanel::getMainPanel()->getGlobalAction("execute_not_validated"));

        ui.kApply->setIcon(menu->icon());
        ui.kApply->setMenu(menu);
        ui.kApply->setPopupMode(QToolButton::InstantPopup);
    }

    ui.kWidgetSelector->setSelectedMode(0);

    connect(ui.kView->getView(), SIGNAL(clickEmptyArea()), this, SLOT(cleanEditor()));
    connect(ui.kView->getView(), SIGNAL(doubleClicked(QModelIndex)), SKGMainPanel::getMainPanel()->getGlobalAction("open"), SLOT(trigger()));
    connect(ui.kView->getView(), SIGNAL(selectionChangedDelayed()), this, SLOT(onSelectionChanged()));

    // Refresh
    connect(getDocument(), SIGNAL(tableModified(QString,int,bool)), this, SLOT(dataModified(QString,int)), Qt::QueuedConnection);
    dataModified("", 0);

    onSelectionChanged();

    // Set Event filters to catch CTRL+ENTER or SHIFT+ENTER
    this->installEventFilter(this);
}

SKGSearchPluginWidget::~SKGSearchPluginWidget()
{
    SKGTRACEINFUNC(1);
}

bool SKGSearchPluginWidget::eventFilter(QObject* iObject, QEvent* iEvent)
{
    if (iEvent && iEvent->type() == QEvent::KeyPress) {
        QKeyEvent* keyEvent = static_cast<QKeyEvent*>(iEvent);
        if ((keyEvent->key() == Qt::Key_Return || keyEvent->key() == Qt::Key_Enter) && iObject == this) {
            if (QApplication::keyboardModifiers() &Qt::ControlModifier && ui.kAdd->isEnabled()) {
                ui.kAdd->click();
            } else if (QApplication::keyboardModifiers() &Qt::ShiftModifier && ui.kUpdate->isEnabled()) {
                ui.kUpdate->click();
            }
        }
    }

    return false;
}

QString SKGSearchPluginWidget::getState()
{
    SKGTRACEINFUNC(10);
    QDomDocument doc("SKGML");
    QDomElement root = doc.createElement("parameters");
    doc.appendChild(root);
    root.setAttribute("currentPage", SKGServices::intToString(ui.kWidgetSelector->getSelectedMode()));
    root.setAttribute("view", ui.kView->getState());
    return doc.toString();
}

void SKGSearchPluginWidget::setState(const QString& iState)
{
    SKGTRACEINFUNC(10);
    QDomDocument doc("SKGML");
    doc.setContent(iState);
    QDomElement root = doc.documentElement();

    QString currentPage = root.attribute("currentPage");
    QString xmlsearchcondition = root.attribute("xmlsearchcondition");

    if (currentPage.isEmpty()) {
        currentPage = '0';
    }

    ui.kWidgetSelector->setSelectedMode(SKGServices::stringToInt(currentPage));
    ui.kQueryCreator->setXMLCondition(xmlsearchcondition);
    ui.kView->setState(root.attribute("view"));
}

QString SKGSearchPluginWidget::getDefaultStateAttribute()
{
    return "SKGSEARCH_DEFAULT_PARAMETERS";
}

QWidget* SKGSearchPluginWidget::mainWidget()
{
    return ui.kView->getView();
}

SKGObjectBase::SKGListSKGObjectBase SKGSearchPluginWidget::getSelectedObjects()
{
    SKGObjectBase::SKGListSKGObjectBase list = ui.kView->getView()->getSelectedObjects();

    // Sort selection by f_sortorder. It's mandatory for reorder functions
    qStableSort(list.begin(), list.end());

    return list;
}

int SKGSearchPluginWidget::getNbSelectedObjects()
{
    return ui.kView->getView()->getNbSelectedObjects();
}

void SKGSearchPluginWidget::dataModified(const QString& iTableName, int iIdTransaction)
{
    SKGTRACEINFUNC(1);
    Q_UNUSED(iIdTransaction);

    // Refresh account list
    if (iTableName == "unit" || iTableName.isEmpty()) {
        ui.kAlarmUnit->setText(static_cast<SKGDocumentBank*>(getDocument())->getPrimaryUnit().Symbol);
    }
}

void SKGSearchPluginWidget::onAddRule()
{
    SKGError err;
    SKGTRACEINFUNCRC(1, err);
    {
        SKGRuleObject rule;
        {
            SKGBEGINTRANSACTION(*getDocument(), i18nc("Noun, name of the user action", "Search and process creation"), err);
            rule = SKGRuleObject(getDocument());
            IFOKDO(err, rule.setXMLSearchDefinition(ui.kQueryCreator->getXMLCondition()))
            IFOKDO(err, rule.setOrder(-1))

            QString xml = getXMLActionDefinition();
            IFOKDO(err, rule.setActionType(xml.isEmpty() ? SKGRuleObject::SEARCH : SKGRuleObject::ActionType(ui.kWidgetSelector->getSelectedMode())))
            IFOKDO(err, rule.setXMLActionDefinition(xml))
            IFOKDO(err, rule.save())
        }

        // status bar
        IFOK(err) {
            err = SKGError(0, i18nc("Successful message after an user action", "Search and process created"));
            ui.kView->getView()->selectObject(rule.getUniqueID());
        } else {
            err.addError(ERR_FAIL, i18nc("Error message",  "Search and process creation failed"));
        }
    }

    // Display error
    SKGMainPanel::displayErrorMessage(err);
}

void SKGSearchPluginWidget::onOpen()
{
    SKGError err;
    SKGTRACEINFUNCRC(1, err);
    SKGRuleObject rule;
    QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
    rule = SKGRuleObject(getDocument());
    IFOKDO(err, rule.setXMLSearchDefinition(ui.kQueryCreator->getXMLCondition()))
    IFOKDO(err, rule.setOrder(-1))

    QString xml = getXMLActionDefinition();
    IFOKDO(err, rule.setActionType(xml.isEmpty() ? SKGRuleObject::SEARCH : SKGRuleObject::ActionType(ui.kWidgetSelector->getSelectedMode())))
    IFOKDO(err, rule.setXMLActionDefinition(xml))
    IFOK(err) open(rule, (sender() == ui.kSearch ? SKGSearchPluginWidget::TABLE : SKGSearchPluginWidget::REPORT));
    QApplication::restoreOverrideCursor();

    // Display error
    SKGMainPanel::displayErrorMessage(err);
}

void SKGSearchPluginWidget::onModifyRule()
{
    SKGError err;
    SKGTRACEINFUNCRC(1, err);
    {
        SKGBEGINTRANSACTION(*getDocument(), i18nc("Noun, name of the user action", "Search and process update"), err);
        SKGObjectBase::SKGListSKGObjectBase rules = getSelectedObjects();
        if (rules.count() == 1) {
            SKGRuleObject rule(rules.at(0));
            IFOKDO(err, rule.setXMLSearchDefinition(ui.kQueryCreator->getXMLCondition()))
            QString xml = getXMLActionDefinition();
            IFOKDO(err, rule.setActionType(xml.isEmpty() ? SKGRuleObject::SEARCH : SKGRuleObject::ActionType(ui.kWidgetSelector->getSelectedMode())))
            IFOKDO(err, rule.setXMLActionDefinition(xml))
            IFOKDO(err, rule.save())
        }
    }

    // status bar
    IFOKDO(err, SKGError(0, i18nc("Successful message after an user action", "Search and process updated")))
    else {
        err.addError(ERR_FAIL, i18nc("Error message",  "Search and process update failed"));
    }

    // Display error
    SKGMainPanel::displayErrorMessage(err);
}

void SKGSearchPluginWidget::onSelectionChanged()
{
    SKGObjectBase::SKGListSKGObjectBase selection = getSelectedObjects();
    int nbSel = selection.count();

    ui.kTopBtn->setEnabled(nbSel > 0);
    ui.kUpBtn->setEnabled(nbSel > 0);
    ui.kDownBtn->setEnabled(nbSel > 0);
    ui.kBottomBtn->setEnabled(nbSel > 0);
    ui.kUpdate->setEnabled(nbSel == 1);
    ui.kApply->setEnabled(nbSel > 0);

    if (nbSel > 0) {
        SKGRuleObject rule(selection.at(0));
        ui.kQueryCreator->setXMLCondition(rule.getXMLSearchDefinition());

        int index = qMax(0, static_cast<int>(rule.getActionType()));
        if (ui.kWidgetSelector->getSelectedMode() != -1) {
            ui.kWidgetSelector->setSelectedMode(index);
        }
        if (index == 1) {
            // Set update mode
            ui.kActionCreator->setXMLCondition(rule.getXMLActionDefinition());
        } else if (index == 2) {
            // Set alarm mode
            QDomDocument doc("SKGML");
            doc.setContent(rule.getXMLActionDefinition());

            QDomElement element = doc.documentElement();
            QDomElement elementLine = element.firstChild().toElement();
            QDomElement elementElement = elementLine.firstChild().toElement();
            ui.kAlarmAmount->setValue(SKGServices::stringToDouble(elementElement.attribute("value")));
            ui.kAlarmMessage->setText(elementElement.attribute("value2"));
        } else if (index == 3) {
            // Set template mode
            QDomDocument doc("SKGML");
            doc.setContent(rule.getXMLActionDefinition());

            QDomElement element = doc.documentElement();
            QDomElement elementLine = element.firstChild().toElement();
            QDomElement elementElement = elementLine.firstChild().toElement();
            ui.kTemplate->setCurrentIndex(ui.kTemplate->findData(elementElement.attribute("value")));
        }
    }

    onEditorModified();

    Q_EMIT selectionChanged();
}

void SKGSearchPluginWidget::onTop()
{
    SKGError err;
    SKGTRACEINFUNCRC(1, err);

    // Get rules
    SKGObjectBase::SKGListSKGObjectBase  rules = getSelectedObjects();
    int nb = rules.count();
    {
        SKGBEGINPROGRESSTRANSACTION(*getDocument(), i18nc("Noun, name of the user action", "Search update"), err, nb);
        for (int i = nb - 1; !err && i >= 0; --i) {
            SKGRuleObject rule(rules.at(i));

            double order = 1;
            SKGStringListList result;
            err = getDocument()->executeSelectSqliteOrder("SELECT min(f_sortorder) from rule", result);
            if (!err && result.count() == 2) {
                order = SKGServices::stringToDouble(result.at(1).at(0)) - 1;
            }

            IFOKDO(err, rule.setOrder(order))
            IFOKDO(err, rule.save())
            IFOKDO(err, getDocument()->stepForward(i + 1))
        }
    }

    // status bar
    IFOKDO(err, SKGError(0, i18nc("Successful message after an user action", "Search updated")))
    else {
        err.addError(ERR_FAIL, i18nc("Error message",  "Search update failed"));
    }

    // Display error
    SKGMainPanel::displayErrorMessage(err);
}

void SKGSearchPluginWidget::onUp()
{
    SKGError err;
    SKGTRACEINFUNCRC(1, err);

    // Get rules
    SKGObjectBase::SKGListSKGObjectBase  rules = getSelectedObjects();
    int nb = rules.count();
    {
        SKGBEGINPROGRESSTRANSACTION(*getDocument(), i18nc("Noun, name of the user action", "Search update"), err, nb);
        for (int i = 0; !err && i < nb; ++i) {
            SKGRuleObject rule(rules.at(i));

            double order = rule.getOrder();
            SKGStringListList result;
            err = getDocument()->executeSelectSqliteOrder("SELECT f_sortorder from rule where f_sortorder<" % SKGServices::doubleToString(order) % " ORDER BY f_sortorder DESC", result);
            IFOK(err) {
                if (result.count() == 2) {
                    order = SKGServices::stringToDouble(result.at(1).at(0)) - 1;
                } else if (result.count() >= 2) {
                    order = (SKGServices::stringToDouble(result.at(1).at(0)) + SKGServices::stringToDouble(result.at(2).at(0))) / 2;
                }
            }

            IFOKDO(err, rule.setOrder(order))
            IFOKDO(err, rule.save())
            IFOKDO(err, getDocument()->stepForward(i + 1))
        }
    }

    // status bar
    IFOKDO(err, SKGError(0, i18nc("Successful message after an user action", "Search updated")))
    else {
        err.addError(ERR_FAIL, i18nc("Error message",  "Search update failed"));
    }

    // Display error
    SKGMainPanel::displayErrorMessage(err);
}

void SKGSearchPluginWidget::onDown()
{
    SKGError err;
    SKGTRACEINFUNCRC(1, err);

    // Get rules
    SKGObjectBase::SKGListSKGObjectBase  rules = getSelectedObjects();
    int nb = rules.count();
    {
        SKGBEGINPROGRESSTRANSACTION(*getDocument(), i18nc("Noun, name of the user action", "Search update"), err, nb);
        for (int i = nb - 1; !err && i >= 0; --i) {
            SKGRuleObject rule(rules.at(i));

            double order = rule.getOrder();
            SKGStringListList result;
            err = getDocument()->executeSelectSqliteOrder("SELECT f_sortorder from rule where f_sortorder>" % SKGServices::doubleToString(order) % " ORDER BY f_sortorder ASC", result);
            IFOK(err) {
                if (result.count() == 2) {
                    order = SKGServices::stringToDouble(result.at(1).at(0)) + 1;
                } else if (result.count() >= 2) {
                    order = (SKGServices::stringToDouble(result.at(1).at(0)) + SKGServices::stringToDouble(result.at(2).at(0))) / 2;
                }
            }

            IFOKDO(err, rule.setOrder(order))
            IFOKDO(err, rule.save())
            IFOKDO(err, getDocument()->stepForward(i + 1))
        }
    }

    // status bar
    IFOKDO(err, SKGError(0, i18nc("Successful message after an user action", "Search updated")))
    else {
        err.addError(ERR_FAIL, i18nc("Error message",  "Search update failed"));
    }

    // Display error
    SKGMainPanel::displayErrorMessage(err);
}

void SKGSearchPluginWidget::onBottom()
{
    SKGError err;
    SKGTRACEINFUNCRC(1, err);

    // Get rules
    SKGObjectBase::SKGListSKGObjectBase  rules = getSelectedObjects();
    int nb = rules.count();
    {
        SKGBEGINPROGRESSTRANSACTION(*getDocument(), i18nc("Noun, name of the user action", "Search update"), err, nb);
        for (int i = 0; !err && i < nb; ++i) {
            SKGRuleObject rule(rules.at(i));

            double order = 1;
            SKGStringListList result;
            err = getDocument()->executeSelectSqliteOrder("SELECT max(f_sortorder) from rule", result);
            if (!err && result.count() == 2) {
                order = SKGServices::stringToDouble(result.at(1).at(0)) + 1;
            }

            IFOKDO(err, rule.setOrder(order))
            IFOKDO(err, rule.save())
            IFOKDO(err, getDocument()->stepForward(i + 1))
        }
    }

    // status bar
    IFOKDO(err, SKGError(0, i18nc("Successful message after an user action", "Search updated")))
    else {
        err.addError(ERR_FAIL, i18nc("Error message",  "Search update failed"));
    }

    // Display error
    SKGMainPanel::displayErrorMessage(err);
}

void SKGSearchPluginWidget::open(const SKGRuleObject& iRule, OpenMode iMode)
{
    _SKGTRACEINFUNC(10);

    // Build where clause and title
    QString wc = "i_SUBOPID in (SELECT i_SUBOPID FROM v_operation_prop WHERE " % iRule.getSelectSqlOrder() % ')';
    QString title = i18nc("Noun, a list of items", "Sub operations corresponding to rule '%1'",  iRule.getSearchDescription());

    // Call operation plugin
    QDomDocument doc("SKGML");
    doc.setContent(SKGMainPanel::getMainPanel()->getDocument()->getParameter(iMode == TABLE ? "SKGOPERATION_CONSOLIDATED_DEFAULT_PARAMETERS" : "SKGREPORT_DEFAULT_PARAMETERS"));
    QDomElement root = doc.documentElement();
    if (root.isNull()) {
        root = doc.createElement("parameters");
        doc.appendChild(root);
    }

    root.setAttribute("operationWhereClause", wc);
    root.setAttribute("title", title);
    root.setAttribute("title_icon", "edit-find");

    if (iMode == TABLE) {
        root.setAttribute("operationTable", "v_suboperation_consolidated");
        root.setAttribute("currentPage", "-1");
        SKGMainPanel::getMainPanel()->openPage(SKGMainPanel::getMainPanel()->getPluginByName("Skrooge operation plugin"), -1, doc.toString());
    } else {
        root.setAttribute("period", "0");
        SKGMainPanel::getMainPanel()->openPage(SKGMainPanel::getMainPanel()->getPluginByName("Skrooge report plugin"), -1, doc.toString());
    }
}

void SKGSearchPluginWidget::onEditorModified()
{
    SKGObjectBase::SKGListSKGObjectBase selection = getSelectedObjects();
    int nbSelect = selection.count();
    ui.kUpdate->setEnabled(nbSelect == 1);
    ui.kQueryInfo->setText("");

    if (nbSelect == 1) {
        SKGRuleObject rule(selection.at(0));

        // Build where clause and title
        QString wc = rule.getSelectSqlOrder();

        SKGStringListList result;
        int vAll = 0;
        getDocument()->executeSelectSqliteOrder("SELECT count(distinct(id)) from v_operation_prop WHERE " % wc, result);
        if (result.count() == 2) {
            vAll = SKGServices::stringToInt(result.at(1).at(0));
        }

        int vImported = 0;
        getDocument()->executeSelectSqliteOrder("SELECT count(distinct(id)) from v_operation_prop WHERE t_imported!='N' AND " % wc, result);
        if (result.count() == 2) {
            vImported = SKGServices::stringToInt(result.at(1).at(0));
        }

        int vNotValidatedl = 0;
        getDocument()->executeSelectSqliteOrder("SELECT count(distinct(id)) from v_operation_prop WHERE t_imported='P' AND " % wc, result);
        if (result.count() == 2) {
            vNotValidatedl = SKGServices::stringToInt(result.at(1).at(0));
        }

        ui.kQueryInfo->setText(i18np("%1 operation found (%2 imported, %3 not yet validated).", "%1 operations found (%2 imported, %3 not yet validated).", vAll, vImported, vNotValidatedl));
    }
}

void SKGSearchPluginWidget::cleanEditor()
{
    if (getNbSelectedObjects() == 0) {
        ui.kQueryCreator->clearContents();
        ui.kActionCreator->clearContents();
    }
}

QString SKGSearchPluginWidget::getXMLActionDefinition()
{
    QString output;
    if (ui.kWidgetSelector->getSelectedMode() == 1) {
        // Mode update
        output = ui.kActionCreator->getXMLCondition();
    } else if (ui.kWidgetSelector->getSelectedMode() == 2) {
        // Mode alarm
        QDomDocument doc("SKGML");
        QDomElement element = doc.createElement("element");
        doc.appendChild(element);

        QDomElement elementLine = doc.createElement("element");
        element.appendChild(elementLine);

        QDomElement elementElement = doc.createElement("element");
        elementLine.appendChild(elementElement);

        elementElement.setAttribute("attribute", "f_REALCURRENTAMOUNT");
        elementElement.setAttribute("operator", "ABS(TOTAL(#ATT#))#OP##V1#,ABS(TOTAL(#ATT#)), #V1#, '#V2S#'");
        elementElement.setAttribute("operator2", ">=");
        elementElement.setAttribute("value", SKGServices::doubleToString(ui.kAlarmAmount->value()));
        elementElement.setAttribute("value2", ui.kAlarmMessage->text());

        output = doc.toString();
    } else if (ui.kWidgetSelector->getSelectedMode() == 3) {
        // Mode template
        QDomDocument doc("SKGML");
        QDomElement element = doc.createElement("element");
        doc.appendChild(element);

        QDomElement elementLine = doc.createElement("element");
        element.appendChild(elementLine);

        QDomElement elementElement = doc.createElement("element");
        elementLine.appendChild(elementElement);

        elementElement.setAttribute("attribute", "id");
        elementElement.setAttribute("operator", "APPLYTEMPLATE(#V1#)");
        elementElement.setAttribute("value", ui.kTemplate->itemData(ui.kTemplate->currentIndex()).toString());
        elementElement.setAttribute("value2", ui.kTemplate->currentText());

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

bool SKGSearchPluginWidget::isEditor()
{
    return true;
}

void SKGSearchPluginWidget::activateEditor()
{
    if (ui.kWidgetSelector->getSelectedMode() == -1) {
        ui.kWidgetSelector->setSelectedMode(0);
    }
}

#include "skgsearchpluginwidget.moc"


