/***************************************************************************
 *   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
 * This file is a widget for dashboard.
 *
 * @author Stephane MANKOWSKI / Guillaume DE BURE
 */
#include "skgcategoriesboardwidget.h"
#include "skgtraces.h"
#include "skgdocumentbank.h"
#include "skgmainpanel.h"

#include <KAction>

#include <QDomDocument>

SKGCategoriesBoardWidget::SKGCategoriesBoardWidget(SKGDocument* iDocument)
    : SKGWidget(iDocument), m_mode(0)
{
    SKGTRACEIN(10, "SKGCategoriesBoardWidget::SKGCategoriesBoardWidget");

    ui.setupUi(this);

    //Create menu
    setContextMenuPolicy(Qt::ActionsContextMenu);

    m_previousMonth = new KAction(i18nc("Report for the previous month", "Previous month"), this);
    m_previousMonth->setCheckable(true);
    m_previousMonth->setChecked(true);
    connect(m_previousMonth, SIGNAL(triggered(bool)), this, SLOT(onModified()));
    addAction(m_previousMonth);

    m_timer.setSingleShot(true);
    connect(&m_timer, SIGNAL(timeout()), this, SLOT(onModified()));
    connect((const QObject*) getDocument(), SIGNAL(transactionSuccessfullyEnded(int)), this, SLOT(onModified()), Qt::QueuedConnection);
}

SKGCategoriesBoardWidget::~SKGCategoriesBoardWidget()
{
    SKGTRACEIN(10, "SKGCategoriesBoardWidget::~SKGCategoriesBoardWidget");
    m_previousMonth = NULL;
}

QString SKGCategoriesBoardWidget::getState()
{
    SKGTRACEIN(10, "SKGCategoriesBoardWidget::getState");
    QDomDocument doc("SKGML");
    QDomElement root = doc.createElement("parameters");
    doc.appendChild(root);

    //Get state
    root.setAttribute("mode", SKGServices::intToString(m_mode));
    root.setAttribute("previousMonth", m_previousMonth && m_previousMonth->isChecked() ? "Y" : "N");

    return doc.toString();
}

void SKGCategoriesBoardWidget::setState(const QString& iState)
{
    SKGTRACEIN(10, "SKGCategoriesBoardWidget::setState");
    QDomDocument doc("SKGML");
    doc.setContent(iState);
    QDomElement root = doc.documentElement();

    //Set state
    QString modeS = root.attribute("mode");
    if (!modeS.isEmpty()) m_mode = SKGServices::stringToInt(modeS);

    if (m_previousMonth) m_previousMonth->setChecked(root.attribute("previousMonth") != "N");

    m_timer.start(300);
}

void SKGCategoriesBoardWidget::onModified()
{
    SKGTRACEIN(10, "SKGCategoriesBoardWidget::onModified");

    //Compute parameters
    QDate month = QDate::currentDate();
    month = month.addDays(-month.day() + 1);
    if (m_previousMonth && m_previousMonth->isChecked()) month = month.addMonths(-1);
    QDate previousMonth = month.addMonths(-1);
    QString monthS = month.toString("yyyy-MM");

    //Set title
    QString title;
    if (m_mode == 0) title = i18nc("Report header",  "5 main categories of expenditure");
    else if (m_mode == 1) title = i18nc("Report header",  "5 main variations");
    else if (m_mode == 2) title = i18nc("Report header",  "Budget");
    ui.kGroup->setTitle(title % " - " % monthS);

    //Set report
    SKGDocumentBank* doc = static_cast<SKGDocumentBank*>(getDocument());
    if (doc) {
        if (m_mode == 0) {
            SKGServices::SKGUnitInfo prim = doc->getPrimaryUnit();
            QVariantList categories = doc->getMainCategories(monthS, 5);
            QString table = "<table>";
            int nb = categories.count();
            for (int i = 0; i < nb; ++i) {
                QVariantList line = categories.at(i).toList();
                if (i == 0) {
                    table += "<tr>"
                             "<th align=\"center\">" % line.at(1).toString() % "</th>"
                             "<th align=\"center\">" % line.at(2).toString() % "</th>"
                             "</tr>";
                } else {
                    table += "<tr>"
                             "<td>" % line.at(1).toString() % "</td>"
                             "<td align=\"right\">" % doc->formatMoney(line.at(2).toDouble(), prim) % "</td>"
                             "</tr>";
                }
            }
            table += "</table>";

            ui.kText->setText(table);
        } else if (m_mode == 1) {
            QString html;
            QStringList list = doc->get5MainCategoriesVariationList(monthS, previousMonth.toString("yyyy-MM"));
            int nbval = list.count();
            for (int i = 0; i < nbval; ++i) {
                html += list.at(i) % "<br>";
            }
            ui.kText->setText(html);
        } else if (m_mode == 2) {
            SKGServices::SKGUnitInfo prim = doc->getPrimaryUnit();
            QVariantList budget = doc->getBudget(monthS);
            QString table = "<table>";
            int nb = budget.count();
            for (int i = 0; i < nb; ++i) {
                QVariantList line = budget.at(i).toList();
                if (i == 0) {
                    table += "<tr>"
                             "<th align=\"center\">" % line.at(1).toString() % "</th>"
                             "<th align=\"center\">" % line.at(2).toString() % "</th>"
                             "<th align=\"center\">" % line.at(3).toString() % "</th>"
                             "<th align=\"center\">" % line.at(4).toString() % "</th>"
                             "</tr>";
                } else {
                    QString v5 = doc->formatMoney(line.at(5).toDouble(), prim);
                    QString v2 = doc->formatMoney(line.at(2).toDouble(), prim);
                    table += "<tr>"
                             "<td>" % line.at(1).toString() % "</td>"
                             "<td align=\"right\">" % (v2 == v5 ? v5 : v5 % "<br/><s><small>" % v2 % "</small></s>") % "</td>"
                             "<td align=\"right\">" % doc->formatMoney(line.at(3).toDouble(), prim) % "</td>"
                             "<td align=\"right\">" % doc->formatMoney(line.at(4).toDouble(), prim) % "</td>"
                             "</tr>";
                }
            }
            table += "</table>";
            ui.kText->setText(!nb ? i18nc("Message", "No budget defined<br>on the <a href=\"___\">\"Budget\"</a> page.") : table);
        }
    }

    //No widget if no account
    bool exist = false;
    getDocument()->existObjects("account", "", exist);
    if (parentWidget()) setVisible(exist);
}

void SKGCategoriesBoardWidget::onOpen(const QString& iLink)
{
    Q_UNUSED(iLink);
    QDomDocument doc("SKGML");
    doc.setContent(getDocument()->getParameter("SKGBUDGET_DEFAULT_PARAMETERS"));
    SKGMainPanel::getMainPanel()->openPage(SKGMainPanel::getMainPanel()->getPluginByName("Skrooge budget plugin"), -1, doc.toString());
}
#include "skgcategoriesboardwidget.moc"
