/***************************************************************************
 *   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 "skgobjectmodel.h"
#include "skgmainpanel.h"
#include "skgtraces.h"
#include "skgdocument.h"
#include "skgbankincludes.h"
#include "skgservices.h"
#include "skgcategoryobject.h"
#include "skgruleobject.h"

#include <kstandarddirs.h>

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

SKGSearchPluginWidget::SKGSearchPluginWidget(SKGDocument* iDocument)
    : SKGTabPage(iDocument)
{
    SKGTRACEIN(1, "SKGSearchPluginWidget::SKGSearchPluginWidget");
    if (!iDocument) return;

    ui.setupUi(this);

    ui.kView->getShowWidget()->addItem("search", i18nc("Noun, a search", "Search"), "edit-find", "t_action_type='S'", "", "", "");
    ui.kView->getShowWidget()->addItem("update", i18nc("Noun, a modification", "Update"), "view-refresh", "t_action_type='U'", "", "", "");
    ui.kView->getShowWidget()->addItem("alarm", i18nc("Noun, an alarm", "Alarm"), "dialog-warning", "t_action_type='A'", "", "", "");
    ui.kView->getShowWidget()->addSeparator();
    ui.kView->getShowWidget()->addItem("highlighted", i18nc("Adjective, an highlighted item", "Highlighted"), "bookmarks", "t_bookmarked='Y'", "", "", "");
    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 edition 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 edition 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 edition panel for alarm"), list);
    }

    //Fill combo boxes
    QStringList attributeForQuery;
    attributeForQuery << "d_date" << "i_number" << "t_mode" << "t_PAYEE" << "t_comment" << "t_REALCOMMENT" << "t_REALCATEGORY" << "t_status" << "t_bookmarked" << "t_imported" << "t_ACCOUNT" << "f_REALCURRENTAMOUNT" << "t_REALREFUND" << "f_BALANCE";
    QStringList attributeForUpdate;
    attributeForUpdate << "i_number" << "t_mode" << "t_PAYEE" << "t_comment" << "t_status" << "t_bookmarked" << "t_imported" << "t_REALCOMMENT" << "t_REALCATEGORY" << "t_ACCOUNT" << "t_REALREFUND";

    //Adding properties
    QStringList properties;
    iDocument->getDistinctValues("parameters", "t_name", "t_uuid_parent like '%-operation'", 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_operation_consolidated", attributeForQuery);
    ui.kActionCreator->setParameters(iDocument, "v_operation_consolidated", attributeForUpdate, true);

    //Bind operation view
    ui.kView->setModel(new SKGObjectModel(static_cast<SKGDocumentBank*>(getDocument()), "v_rule", "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((const QObject*) getDocument(), SIGNAL(tableModified(QString,int)), 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()
{
    SKGTRACEIN(1, "SKGSearchPluginWidget::~SKGSearchPluginWidget");
}

bool SKGSearchPluginWidget::eventFilter(QObject* object, QEvent* event)
{
    if (event && event->type() == QEvent::KeyPress) {
        QKeyEvent* keyEvent = (QKeyEvent*) event;
        if ((keyEvent->key() == Qt::Key_Return || keyEvent->key() == Qt::Key_Enter) && object == 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()
{
    SKGTRACEIN(10, "SKGSearchPluginWidget::getState");
    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)
{
    SKGTRACEIN(10, "SKGSearchPluginWidget::setState");
    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() const
{
    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)
{
    SKGTRACEIN(1, "SKGSearchPluginWidget::dataModified");
    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;
    SKGTRACEINRC(1, "SKGSearchPluginWidget::onAddRule", err);
    {
        SKGRuleObject rule;
        {
            SKGBEGINTRANSACTION(*getDocument(), i18nc("Noun, name of the user action", "Search and process creation"), err);
            rule = SKGRuleObject(getDocument());
            if (!err) err = rule.setXMLSearchDefinition(ui.kQueryCreator->getXMLCondition());
            if (!err) err = rule.setOrder(-1);

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

        //status bar
        if (!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;
    SKGTRACEINRC(1, "SKGSearchPluginWidget::onOpen", err);
    SKGRuleObject rule;
    QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
    rule = SKGRuleObject(getDocument());
    if (!err) err = rule.setXMLSearchDefinition(ui.kQueryCreator->getXMLCondition());
    if (!err) err = rule.setOrder(-1);

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

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

void SKGSearchPluginWidget::onModifyRule()
{
    SKGError err;
    SKGTRACEINRC(1, "SKGSearchPluginWidget::onModifyRule", 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);
            if (!err) err = rule.setXMLSearchDefinition(ui.kQueryCreator->getXMLCondition());
            QString xml = getXMLActionDefinition();
            if (!err) err = rule.setActionType(xml.isEmpty() ? SKGRuleObject::SEARCH : SKGRuleObject::ActionType(ui.kWidgetSelector->getSelectedMode()));
            if (!err) err = rule.setXMLActionDefinition(xml);
            if (!err) err = rule.save();
        }
    }

    //status bar
    if (!err) 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, ((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"));
        }
    }

    onEditorModified();

    Q_EMIT selectionChanged();
}

void SKGSearchPluginWidget::onTop()
{
    SKGError err;
    SKGTRACEINRC(1, "SKGSearchPluginWidget::onTop", 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;

            if (!err) err = rule.setOrder(order);
            if (!err) err = rule.save();
            if (!err) err = getDocument()->stepForward(i + 1);

        }
    }

    //status bar
    if (!err) 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;
    SKGTRACEINRC(1, "SKGSearchPluginWidget::onUp", 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);
            if (!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;
                }
            }

            if (!err) err = rule.setOrder(order);
            if (!err) err = rule.save();
            if (!err) err = getDocument()->stepForward(i + 1);

        }
    }

    //status bar
    if (!err) 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;
    SKGTRACEINRC(1, "SKGSearchPluginWidget::onDown", 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);
            if (!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;
                }
            }

            if (!err) err = rule.setOrder(order);
            if (!err) err = rule.save();
            if (!err) err = getDocument()->stepForward(i + 1);

        }
    }

    //status bar
    if (!err) 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;
    SKGTRACEINRC(1, "SKGSearchPluginWidget::onBottom", 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;

            if (!err) err = rule.setOrder(order);
            if (!err) err = rule.save();
            if (!err) err = getDocument()->stepForward(i + 1);

        }
    }

    //status bar
    if (!err) 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)
{
    _SKGTRACEIN(10, "SKGSearchPluginWidget::open");

    //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());

    //Open
    if (QApplication::keyboardModifiers() &Qt::ControlModifier && QApplication::keyboardModifiers() &Qt::ShiftModifier) {
        //Call debug plugin
        QDomDocument doc("SKGML");
        QDomElement root = doc.createElement("parameters");
        doc.appendChild(root);
        root.setAttribute("sqlOrder", "SELECT * from v_operation_consolidated WHERE " % wc);

        SKGMainPanel::getMainPanel()->openPage(SKGMainPanel::getMainPanel()->getPluginByName("Debug plugin"), -1, doc.toString());
    } else {
        //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_operation_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();
    }
    return output;
}

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

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

#include "skgsearchpluginwidget.moc"


