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

#include <QDomDocument>
#include <QKeyEvent>

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

    ui.setupUi(this);

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

    ui.kView->getShowWidget()->addItem("opened", i18n("Opened"), "", "t_close='N'", "", "", "closed");
    ui.kView->getShowWidget()->addItem("closed", i18n("Closed"), "dialog-close", "t_close='Y'", "", "", "opened");

    ui.kView->getShowWidget()->setDefaultState("opened");

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

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

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

    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);
}

SKGTrackerPluginWidget::~SKGTrackerPluginWidget()
{
    SKGTRACEIN(1, "SKGTrackerPluginWidget::~SKGTrackerPluginWidget");
}

bool SKGTrackerPluginWidget::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 SKGTrackerPluginWidget::onSelectionChanged()
{
    SKGTRACEIN(10, "SKGTrackerPluginWidget::onSelectionChanged");

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

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

    onEditorModified();
    Q_EMIT selectionChanged();
}

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

void SKGTrackerPluginWidget::setState(const QString& iState)
{
    SKGTRACEIN(10, "SKGTrackerPluginWidget::setState");
    QDomDocument doc("SKGML");
    doc.setContent(iState);
    QDomElement root = doc.documentElement();
    ui.kView->setState(root.attribute("view"));
}

QString SKGTrackerPluginWidget::getDefaultStateAttribute()
{
    return "SKGREFUND_DEFAULT_PARAMETERS";
}

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

void SKGTrackerPluginWidget::onEditorModified()
{
    _SKGTRACEIN(10, "SKGTrackerPluginWidget::onEditorModified");
    int nb = ui.kView->getView()->getNbSelectedObjects();
    ui.kModifyButton->setEnabled(!ui.kNameInput->text().isEmpty() && nb >= 1);
    ui.kAddButton->setEnabled(!ui.kNameInput->text().isEmpty());
}

void SKGTrackerPluginWidget::dataModified(const QString& iTableName, int iIdTransaction)
{
    SKGTRACEIN(10, "SKGTrackerPluginWidget::dataModified");
    Q_UNUSED(iIdTransaction);

    if (iTableName == "refund" || iTableName.isEmpty()) {
        //Set completions
        SKGMainPanel::fillWithDistinctValue(ui.kNameInput, getDocument(), "refund", "t_name", "", true);
        SKGMainPanel::fillWithDistinctValue(ui.kCommentEdit, getDocument(), "refund", "t_comment", "", true);
    }
}

void SKGTrackerPluginWidget::onAddTracker()
{
    SKGError err;
    _SKGTRACEINRC(10, "SKGTrackerPluginWidget::onAddTracker", err);

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

        err = SKGTrackerObject::createTracker(static_cast<SKGDocumentBank*>(getDocument()), name, tracker);
        if (!err) err = tracker.setComment(ui.kCommentEdit->text());
        if (!err) err = tracker.save();
    }

    //status bar
    if (!err) {
        err = SKGError(0, i18nc("Successful message after an user action", "Tracker '%1' created", name));
        ui.kView->getView()->selectObject(tracker.getUniqueID());
    } else err.addError(ERR_FAIL, i18nc("Error message", "Tracker creation failed"));

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

void SKGTrackerPluginWidget::onModifyTracker()
{
    SKGError err;
    _SKGTRACEINRC(10, "SKGTrackerPluginWidget::onModifyTracker", err);
    //Get Selection
    SKGObjectBase::SKGListSKGObjectBase selection = getSelectedObjects();

    int nb = selection.count();
    {
        SKGBEGINPROGRESSTRANSACTION(*getDocument(), i18nc("Noun, name of the user action", "Tracker update")  , err, nb);
        for (int i = 0; !err && i < nb; ++i) {

            //Modification of object
            SKGTrackerObject tracker = selection[i];
            err = tracker.setName(ui.kNameInput->text());
            if (!err) err = tracker.setComment(ui.kCommentEdit->text());
            if (!err) err = tracker.save();
            if (!err) err = getDocument()->stepForward(i + 1);
        }
    }
    //status bar
    if (!err) err = SKGError(0, i18nc("Successful message after an user action", "Tracker updated"));
    else err.addError(ERR_FAIL, i18nc("Error message", "Tracker update failed"));

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

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

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

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

#include "skgtrackerpluginwidget.moc"
