/***************************************************************************
 *   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 for monthly report
 *
 * @author Stephane MANKOWSKI
 */
#include "skgmonthlyplugin.h"
#include "skgmonthlypluginwidget.h"
#include "skgmonthlyboardwidget.h"
#include "skgdocumentbank.h"
#include "skgmainpanel.h"
#include "skgtraces.h"

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

/**
 * This plugin factory.
 */
K_PLUGIN_FACTORY(SKGMonthlyPluginFactory, registerPlugin<SKGMonthlyPlugin>();)
/**
 * This plugin export.
 */
K_EXPORT_PLUGIN(SKGMonthlyPluginFactory("skrooge_monthly", "skrooge_monthly"))

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

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

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

    m_currentBankDocument = iDocument;

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

    //Create yours actions here
    return true;
}

int SKGMonthlyPlugin::getNbDashboardWidgets()
{
    SKGTRACEIN(1, "SKGMonthlyPlugin::getNbDashboardWidgets");
    return 3;
}

QString SKGMonthlyPlugin::getDashboardWidgetTitle(int iIndex)
{
    SKGTRACEIN(1, "SKGMonthlyPlugin::getDashboardWidgetTitle");
    if (iIndex == 0) return i18nc("Report header",  "5 main categories of expenditure");
    else if (iIndex == 1) return i18nc("Report header",  "5 main variations");
    else if (iIndex == 2) return i18nc("Report header",  "Budget");
    return "";
}

SKGWidget* SKGMonthlyPlugin::getDashboardWidget(int iIndex)
{
    SKGWidget* w = new SKGMonthlyBoardWidget(m_currentBankDocument);

    QDomDocument doc("SKGML");
    QDomElement root = doc.createElement("parameters");
    doc.appendChild(root);
    root.setAttribute("mode", SKGServices::intToString(iIndex));

    w->setState(doc.toString());
    return w;
}

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

QString SKGMonthlyPlugin::title() const
{
    return toolTip();
}

QString SKGMonthlyPlugin::icon() const
{
    return "view-documents-finances";
}

QString SKGMonthlyPlugin::toolTip() const
{
    return i18nc("A tool tip", "Monthly report");
}

int SKGMonthlyPlugin::getOrder() const
{
    return 50;
}

QStringList SKGMonthlyPlugin::tips() const
{
    QStringList output;
    output.push_back(i18nc("Description of a tips", "<p>... you can generate a monthly report.</p>"));
    output.push_back(i18nc("Description of a tips", "<p>... you can download more monthly report templates.</p>"));
    output.push_back(i18nc("Description of a tips", "<p>... you can create and share your own monthly report template.</p>"));
    return output;
}

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

SKGAdviceList SKGMonthlyPlugin::advices() const
{
    SKGTRACEIN(10, "SKGMonthlyPlugin::advices");
    SKGAdviceList output;

    //Check operations not validated
    QString month = QDate::currentDate().toString("yyyy-MM");
    QDate datepreviousmonth = QDate::currentDate().addDays(-QDate::currentDate().day());
    QString previousmonth = datepreviousmonth.toString("yyyy-MM");

    QStringList listCategories;
    QStringList listVariations = qobject_cast< SKGDocumentBank* >(m_currentBankDocument)->get5MainCategoriesVariationList(month, previousmonth, true, &listCategories);

    int nb = listVariations.count();
    for (int i = 0; i < nb; ++i) {
        SKGAdvice ad;
        ad.setUUID("skgmonthlyplugin_maincategoriesvariation|" % listCategories.at(i));
        ad.setPriority(7);
        ad.setShortMessage(i18nc("Advice on making the best (short)", "Important variation for '%1'", listCategories.at(i)));
        ad.setLongMessage(listVariations.at(i));
        QStringList autoCorrections;
        autoCorrections.push_back(i18nc("Advice on making the best (action)", "Open sub operations with category containing '%1'", listCategories.at(i)));
        ad.setAutoCorrections(autoCorrections);
        output.push_back(ad);
    }

    return output;
}

SKGError SKGMonthlyPlugin::executeAdviceCorrection(const QString& iAdviceIdentifier, int iSolution) const
{
    if (m_currentBankDocument && iAdviceIdentifier.startsWith(QLatin1String("skgmonthlyplugin_maincategoriesvariation|"))) {
        //Get parameters
        QString category = iAdviceIdentifier.right(iAdviceIdentifier.length() - 41);
        QString month = QDate::currentDate().toString("yyyy-MM");

        //Call operation plugin
        QDomDocument doc("SKGML");
        doc.setContent(m_currentBankDocument->getParameter("SKGOPERATION_CONSOLIDATED_DEFAULT_PARAMETERS"));
        QDomElement root = doc.documentElement();
        if (root.isNull()) {
            root = doc.createElement("parameters");
            doc.appendChild(root);
        }

        root.setAttribute("operationTable", "v_operation_consolidated");
        root.setAttribute("operationWhereClause", "d_DATEMONTH='" % month % "' AND t_REALCATEGORY='" % SKGServices::stringToSqlString(category) % '\'');
        root.setAttribute("title", i18nc("Noun, a list of items", "Sub operations with category containing '%1'",  category));
        root.setAttribute("title_icon", "skrooge_category");
        root.setAttribute("currentPage", "-1");

        SKGMainPanel::getMainPanel()->openPage(SKGMainPanel::getMainPanel()->getPluginByName("Skrooge operation plugin"), -1, doc.toString());
        return SKGError();
    }

    return SKGInterfacePlugin::executeAdviceCorrection(iAdviceIdentifier, iSolution);
}

#include "skgmonthlyplugin.moc"
