/***************************************************************************
 *   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 track operations.
 *
 * @author Stephane MANKOWSKI
 */
#include "skgpayeepluginwidget.h"

#include <KAction>

#include <QDomDocument>
#include <QKeyEvent>

#include "skgmainpanel.h"
#include "skgtraces.h"
#include "skgobjectmodel.h"
#include "skgdocumentbank.h"
#include "skgpayeeobject.h"
#include "skgtransactionmng.h"

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

    ui.setupUi(this);

    // Set show widget
    ui.kView->getShowWidget()->addGroupedItem("all", i18n("All"), "", "", "", Qt::META + Qt::Key_A);
    ui.kView->getShowWidget()->addGroupedItem("income", i18n("Income"), "list-add", "f_CURRENTAMOUNT>=0", "", Qt::META + Qt::Key_Plus);
    ui.kView->getShowWidget()->addGroupedItem("expenditure", i18n("Expenditure"), "list-remove", "f_CURRENTAMOUNT<=0", "", Qt::META + Qt::Key_Minus);
    ui.kView->getShowWidget()->addGroupedItem("highlighted", i18n("Highlighted"), "bookmarks", "t_bookmarked='Y'", "", Qt::META + Qt::Key_H);
    ui.kView->getShowWidget()->setDefaultState("all");

    ui.kNameLbl->setText(i18n("%1:", iDocument->getDisplay("t_name")));
    ui.kAddressLabel->setText(i18n("%1:", iDocument->getDisplay("t_address")));

    ui.kAddButton->setIcon(KIcon("list-add"));
    ui.kModifyButton->setIcon(KIcon("dialog-ok-apply"));
    ui.kDeleteUnusedButton->setIcon(KIcon("edit-delete"));

    ui.kView->setModel(new SKGObjectModel(static_cast<SKGDocumentBank*>(getDocument()), "v_payee_display", "1=0", this, "", false));
    ui.kView->getView()->resizeColumnToContents(0);

    // 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("edit_find");
        ui.kView->getView()->insertGlobalAction();
        ui.kView->getView()->insertGlobalAction("edit_delete");
        ui.kView->getView()->insertGlobalAction();
        ui.kView->getView()->insertGlobalAction("edit_switch_highlight");
    }
    connect(getDocument(), SIGNAL(tableModified(QString,int,bool)), this, SLOT(dataModified(QString,int,bool)), Qt::QueuedConnection);
    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()));

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

    dataModified("", 0);
}

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

bool SKGPayeePluginWidget::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.kAddButton->isEnabled()) {
                ui.kAddButton->click();
            } else if (QApplication::keyboardModifiers() &Qt::ShiftModifier && ui.kModifyButton->isEnabled()) {
                ui.kModifyButton->click();
            }
        }
    }

    return false;
}

void SKGPayeePluginWidget::onSelectionChanged()
{
    SKGTRACEINFUNC(10);

    int nbSelect = ui.kView->getView()->getNbSelectedObjects();
    if (nbSelect == 1) {
        SKGPayeeObject obj(ui.kView->getView()->getFirstSelectedObject());

        ui.kNameInput->setText(obj.getName());
        ui.kAddressEdit->setText(obj.getAddress());
    } else if (nbSelect > 1) {
        ui.kNameInput->setText(NOUPDATE);
        ui.kAddressEdit->setText(NOUPDATE);
    }

    onEditorModified();
    Q_EMIT selectionChanged();
}

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

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

    ui.kView->setFilter(KIcon(root.attribute("title_icon")), root.attribute("title"), root.attribute("whereClause"));
    ui.kView->setState(root.attribute("view"));
}

QString SKGPayeePluginWidget::getDefaultStateAttribute()
{
    return "SKGPAYEE_DEFAULT_PARAMETERS";
}

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

void SKGPayeePluginWidget::onEditorModified()
{
    _SKGTRACEINFUNC(10);
    int nb = getNbSelectedObjects();
    ui.kModifyButton->setEnabled(!ui.kNameInput->text().isEmpty() && nb >= 1);
    ui.kAddButton->setEnabled(!ui.kNameInput->text().isEmpty());
}

void SKGPayeePluginWidget::dataModified(const QString& iTableName, int iIdTransaction, bool iLightTransaction)
{
    SKGTRACEINFUNC(10);
    Q_UNUSED(iIdTransaction);

    if (!iLightTransaction) {
        if (iTableName == "payee" || iTableName.isEmpty()) {
            // Set completions
            SKGMainPanel::fillWithDistinctValue(ui.kNameInput, getDocument(), "payee", "t_name", "", true);
            SKGMainPanel::fillWithDistinctValue(ui.kAddressEdit, getDocument(), "payee", "t_address", "", true);
        }
    }
}

void SKGPayeePluginWidget::onAddPayee()
{
    SKGError err;
    _SKGTRACEINFUNCRC(10, err);

    QString name = ui.kNameInput->text();
    SKGPayeeObject payee;
    {
        SKGBEGINTRANSACTION(*getDocument(), i18nc("Noun, name of the user action", "Payee creation '%1'", name)  , err);

        IFOKDO(err, SKGPayeeObject::createPayee(static_cast<SKGDocumentBank*>(getDocument()), name, payee))
        IFOKDO(err, payee.setAddress(ui.kAddressEdit->text()))
        IFOKDO(err, payee.save())

        // Send message
        IFOKDO(err, payee.getDocument()->sendMessage(i18nc("An information message", "The payee '%1' has been added", payee.getDisplayName()), SKGDocument::Hidden));
    }
    // status bar
    IFOK(err) {
        err = SKGError(0, i18nc("Successful message after an user action", "Payee '%1' created", name));
        ui.kView->getView()->selectObject(payee.getUniqueID());
    } else {
        err.addError(ERR_FAIL, i18nc("Error message", "Payee creation failed"));
    }

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

void SKGPayeePluginWidget::onModifyPayee()
{
    SKGError err;
    _SKGTRACEINFUNCRC(10, err);

    // Get Selection
    SKGObjectBase::SKGListSKGObjectBase selection = getSelectedObjects();

    int nb = selection.count();

    {
        SKGBEGINPROGRESSTRANSACTION(*getDocument(), i18nc("Noun, name of the user action", "Payee update")  , err, nb);
        // Is it a massive modification of payees to merge them ?
        if (nb > 1 && ui.kNameInput->text() != NOUPDATE && !ui.kNameInput->text().startsWith(QLatin1String("="))) {
            getDocument()->sendMessage(i18nc("Information message", "You tried to modify all names of selected payees. Payees have been merged."));

            // Do the merge
            SKGPayeeObject payeeObj1(selection[0]);
            for (int i = 1; !err && i < nb; ++i) {
                SKGPayeeObject payeeObj(selection[i]);

                // Send message
                IFOKDO(err, payeeObj.getDocument()->sendMessage(i18nc("An information message", "The payee '%1' has been merged with payee '%2'", payeeObj1.getDisplayName(), payeeObj.getDisplayName()), SKGDocument::Hidden));

                err = payeeObj1.merge(payeeObj);
            }

            // Change selection for the rest of the operation
            selection.clear();
            selection.push_back(payeeObj1);
            nb = 1;
        }

        for (int i = 0; !err && i < nb; ++i) {
            // Modification of object
            SKGPayeeObject payee(selection[i]);
            err = payee.setName(ui.kNameInput->text());
            IFOKDO(err, payee.setAddress(ui.kAddressEdit->text()))
            IFOKDO(err, payee.save())

            // Send message
            IFOKDO(err, payee.getDocument()->sendMessage(i18nc("An information message", "The payee '%1' has been updated", payee.getDisplayName()), SKGDocument::Hidden));
        }
    }

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

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

void SKGPayeePluginWidget::cleanEditor()
{
    if (getNbSelectedObjects() == 0) {
        ui.kNameInput->setText("");
        ui.kAddressEdit->setText("");
    }
}

void SKGPayeePluginWidget::activateEditor()
{
    ui.kNameInput->setFocus();
}

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

void SKGPayeePluginWidget::onDeleteUnused()
{
    QAction* act = SKGMainPanel::getMainPanel()->getGlobalAction("clean_delete_unused_payees");
    if (act) {
        act->trigger();
    }
}
#include "skgpayeepluginwidget.moc"
