/***************************************************************************
 *   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 <QDomDocument>
#include <QKeyEvent>

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

SKGTrackerPluginWidget::SKGTrackerPluginWidget(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("opened", i18n("Opened"), "task-ongoing", "t_close='N'", "", Qt::META + Qt::Key_O);
    ui.kView->getShowWidget()->addGroupedItem("closed", i18n("Closed"), "dialog-close", "t_close='Y'", "", Qt::META + Qt::Key_C);
    ui.kView->getShowWidget()->setDefaultState("opened");

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

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

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

    ui.kView->getView()->resizeColumnToContents(0);

    connect(getDocument(), &SKGDocument::tableModified, this, &SKGTrackerPluginWidget::dataModified, Qt::QueuedConnection);
    connect(ui.kView->getView(), &SKGTreeView::clickEmptyArea, this, &SKGTrackerPluginWidget::cleanEditor);
    connect(ui.kView->getView(), &SKGTreeView::doubleClicked, SKGMainPanel::getMainPanel()->getGlobalAction("open"), &QAction::trigger);
    connect(ui.kView->getView(), &SKGTreeView::selectionChangedDelayed, [ = ] {this->onSelectionChanged();});

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

    dataModified("", 0);
}

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

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

    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()
{
    SKGTRACEINFUNC(10);
    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)
{
    SKGTRACEINFUNC(10);
    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()
{
    return ui.kView->getView();
}

void SKGTrackerPluginWidget::onEditorModified()
{
    _SKGTRACEINFUNC(10);
    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, bool iLightTransaction)
{
    SKGTRACEINFUNC(10);
    Q_UNUSED(iIdTransaction);

    if (!iLightTransaction) {
        if (iTableName == "refund" || iTableName.isEmpty()) {
            // Set completions
            SKGMainPanel::fillWithDistinctValue(QList<QWidget*>() << ui.kNameInput, getDocument(), "refund", "t_name", "", true);
            SKGMainPanel::fillWithDistinctValue(QList<QWidget*>() << ui.kCommentEdit, getDocument(), "refund", "t_comment", "", true);
        }
    }
}

void SKGTrackerPluginWidget::onAddTracker()
{
    SKGError err;
    _SKGTRACEINFUNCRC(10, 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);
        IFOKDO(err, tracker.setComment(ui.kCommentEdit->text()))
        IFOKDO(err, tracker.save())

        // Send message
        IFOKDO(err, tracker.getDocument()->sendMessage(i18nc("An information to the user", "The tracker '%1' have been added", tracker.getDisplayName()), SKGDocument::Hidden));
    }

    // status bar
    IFOK(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;
    _SKGTRACEINFUNCRC(10, 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());
            IFOKDO(err, tracker.setComment(ui.kCommentEdit->text()))
            IFOKDO(err, tracker.save())

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

            IFOKDO(err, getDocument()->stepForward(i + 1))
        }
    }
    // status bar
    IFOKDO(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;
}


