/***************************************************************************
 *   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 "skgmainpanel.h"
#include "skgtraces.h"
#include "skgobjectmodel.h"
#include "skgdocumentbank.h"
#include "skgpayeeobject.h"
#include "skgtransactionmng.h"

#include <KAction>

#include <QDomDocument>
#include <QKeyEvent>

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

    ui.setupUi(this);

    //Set show widget
    ui.kView->getShowWidget()->addGroupedItem("all", i18n("All"));
    ui.kView->getShowWidget()->addGroupedItem("income", i18n("Income"), "list-add", "f_CURRENTAMOUNT>=0");
    ui.kView->getShowWidget()->addGroupedItem("expenditure", i18n("Expenditure"), "list-remove", "f_CURRENTAMOUNT<=0");
    ui.kView->getShowWidget()->addGroupedItem("highlighted", i18n("Highlighted"), "bookmarks", "t_bookmarked='Y'");
    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((const QObject*) getDocument(), SIGNAL(tableModified(QString,int)), this, SLOT(dataModified(QString,int)), 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()
{
    SKGTRACEIN(1, "SKGPayeePluginWidget::~SKGPayeePluginWidget");
}

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

    return false;
}

void SKGPayeePluginWidget::onSelectionChanged()
{
    SKGTRACEIN(10, "SKGPayeePluginWidget::onSelectionChanged");

    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()
{
    SKGTRACEIN(10, "SKGPayeePluginWidget::getState");
    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)
{
    SKGTRACEIN(10, "SKGPayeePluginWidget::setState");
    QDomDocument doc("SKGML");
    doc.setContent(iState);
    QDomElement root = doc.documentElement();
    ui.kView->setState(root.attribute("view"));
}

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

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

void SKGPayeePluginWidget::onEditorModified()
{
    _SKGTRACEIN(10, "SKGPayeePluginWidget::onEditorModified");
    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)
{
    SKGTRACEIN(10, "SKGPayeePluginWidget::dataModified");
    Q_UNUSED(iIdTransaction);

    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;
    _SKGTRACEINRC(10, "SKGPayeePluginWidget::onAddPayee", err);

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

        if (!err) err = SKGPayeeObject::createPayee(static_cast<SKGDocumentBank*>(getDocument()), name, payee);
        if (!err) err = payee.setAddress(ui.kAddressEdit->text());
        if (!err) err = payee.save();
    }
    //status bar
    if (!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;
    _SKGTRACEINRC(10, "SKGPayeePluginWidget::onModifyPayee", 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];
                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());
            if (!err) err = payee.setAddress(ui.kAddressEdit->text());
            if (!err) err = payee.save();
        }
    }

    //status bar
    if (!err) 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()
{
    KAction* act = SKGMainPanel::getMainPanel()->getGlobalAction("edit_delete_unused_payees");
    if (act) act->trigger();
}

#include "skgpayeepluginwidget.moc"


