/***************************************************************************
 *   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 payee operations
 *
 * @author Stephane MANKOWSKI
 */
#include "skgpayeeplugin.h"
#include "skgpayeepluginwidget.h"
#include "skgpayee_settings.h"
#include "skgtraces.h"
#include "skgdocumentbank.h"
#include "skgtransactionmng.h"

#include <kactioncollection.h>
#include <kstandardaction.h>
#include <kaboutdata.h>

/**
 * This plugin factory.
 */
K_PLUGIN_FACTORY(SKGPayeePluginFactory, registerPlugin<SKGPayeePlugin>();)
/**
 * This plugin export.
 */
K_EXPORT_PLUGIN(SKGPayeePluginFactory("skrooge_payee", "skrooge_payee"))

SKGPayeePlugin::SKGPayeePlugin(QObject* iParent, const QVariantList& /*iArg*/) : SKGInterfacePlugin(iParent)
{
    SKGTRACEIN(10, "SKGPayeePlugin::SKGPayeePlugin");
}

SKGPayeePlugin::~SKGPayeePlugin()
{
    SKGTRACEIN(10, "SKGPayeePlugin::~SKGPayeePlugin");
    m_currentBankDocument = NULL;
}

bool SKGPayeePlugin::setupActions(SKGDocument* iDocument, const QStringList& iArgument)
{
    SKGTRACEIN(10, "SKGPayeePlugin::setupActions");
    Q_UNUSED(iArgument);
    if (qobject_cast<SKGDocumentBank*>(iDocument) == NULL) return false;

    m_currentBankDocument = iDocument;

    setComponentData(KGlobal::mainComponent());
    setXMLFile("../skrooge_payee/skrooge_payee.rc");

    //Actions
    KAction* deleteUnusedPayeesAction = new KAction(KIcon("edit-delete"), i18nc("Verb", "Delete unused payees"), this);
    connect(deleteUnusedPayeesAction, SIGNAL(triggered(bool)), SLOT(deleteUnusedPayees()));
    actionCollection()->addAction(QLatin1String("edit_delete_unused_payees"), deleteUnusedPayeesAction);

    if (SKGMainPanel::getMainPanel()) SKGMainPanel::getMainPanel()->registedGlobalAction("edit_delete_unused_payees", deleteUnusedPayeesAction);

    return true;
}

SKGTabPage* SKGPayeePlugin::getWidget()
{
    SKGTRACEIN(10, "SKGPayeePlugin::getWidget");
    return new SKGPayeePluginWidget(m_currentBankDocument);
}

KConfigSkeleton* SKGPayeePlugin::getPreferenceSkeleton()
{
    return skgpayee_settings::self();
}

QString SKGPayeePlugin::title() const
{
    return i18nc("Noun, something that is used to track items", "Payees");
}

QString SKGPayeePlugin::icon() const
{
    return "skrooge_payee";
}

QString SKGPayeePlugin::toolTip() const
{
    return i18nc("A tool tip", "Payees management");
}

int SKGPayeePlugin::getOrder() const
{
    return 28;
}

QStringList SKGPayeePlugin::tips() const
{
    QStringList output;
    output.push_back(i18nc("Description of a tips", "<p>... payees can be merged by drag & drop.</p>"));
    return output;
}

bool SKGPayeePlugin::isInPagesChooser() const
{
    return true;
}

SKGAdviceList SKGPayeePlugin::advices() const
{
    SKGTRACEIN(10, "SKGPayeePlugin::advices");
    SKGAdviceList output;
    //Check unused payee
    bool exist = false;
    m_currentBankDocument->existObjects("payee", "NOT EXISTS (SELECT 1 FROM operation WHERE operation.r_payee_id=payee.id)", exist);
    if (exist) {
        SKGAdvice ad;
        ad.setUUID("skgpayeeplugin_unused");
        ad.setPriority(5);
        ad.setShortMessage(i18nc("Advice on making the best (short)", "Many unused payees"));
        ad.setLongMessage(i18nc("Advice on making the best (long)", "You can improve performances by removing payees for which no operation is registered."));
        QStringList autoCorrections;
        autoCorrections.push_back(i18nc("Advice on making the best (action)", "Delete unused payees"));
        ad.setAutoCorrections(autoCorrections);
        output.push_back(ad);
    }

    return output;
}

SKGError SKGPayeePlugin::executeAdviceCorrection(const QString& iAdviceIdentifier, int iSolution) const
{
    if (iAdviceIdentifier == "skgpayeeplugin_unused") {
        deleteUnusedPayees();
        return SKGError();
    }
    return SKGInterfacePlugin::executeAdviceCorrection(iAdviceIdentifier, iSolution);
}

void SKGPayeePlugin::deleteUnusedPayees() const
{
    SKGError err;
    _SKGTRACEINRC(10, "SKGPayeePlugin::deleteUnusedPayees", err);
    if (m_currentBankDocument) {
        SKGBEGINTRANSACTION(*m_currentBankDocument, i18nc("Noun, name of the user action", "Delete unused payees")  , err);

        //Modification of payee object
        QString sql = "DELETE FROM payee WHERE NOT EXISTS (SELECT 1 FROM operation WHERE operation.r_payee_id=payee.id)";
        err = m_currentBankDocument->executeSqliteOrder(sql);
    }

    //status bar
    if (!err) err = SKGError(0, i18nc("Successful message after an user action", "Unused payees deleted"));
    else err.addError(ERR_FAIL, i18nc("Error message", "Unused payees deletion failed"));

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

#include "skgpayeeplugin.moc"
