/***************************************************************************
 *   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 Skrooge plugin for operation management.
 *
 * @author Stephane MANKOWSKI / Guillaume DE BURE
 */
#include "skgoperationboardwidget.h"
#include "skgdocumentbank.h"
#include "skgtraces.h"
#include "skgservices.h"
#include "skgobjectbase.h"
#include <skgmainpanel.h>

#include <QDomDocument>

#include <kaction.h>
#include <kcolorscheme.h>

SKGOperationBoardWidget::SKGOperationBoardWidget(SKGDocument* iDocument)
    : SKGWidget(iDocument)
{
    SKGTRACEIN(10, "SKGOperationBoardWidget::SKGOperationBoardWidget");

    ui.setupUi(this);

    ui.kIncomeLabel->setText("<a href=\"IC\">" % ui.kIncomeLabel->text() % "</a>");
    ui.kExpenseLabel->setText("<a href=\"EC\">" % ui.kExpenseLabel->text() % "</a>");
    ui.kIncome_previousLabel->setText("<a href=\"IP\">" % ui.kIncome_previousLabel->text() % "</a>");
    ui.kExpense_previousLabel->setText("<a href=\"EP\">" % ui.kExpense_previousLabel->text() % "</a>");

    //Define color style
    KColorScheme scheme(QPalette::Normal);
    QString negative = scheme.foreground(KColorScheme::NegativeText).color().name();
    QString neutral = scheme.foreground(KColorScheme::NeutralText).color().name();
    QString positive = scheme.foreground(KColorScheme::PositiveText).color().name();

    m_negativeStyleSheet = QString(" QProgressBar { text-align: center; padding: 0.5px;} QProgressBar::chunk {text-align: center; border-radius:4px; background-color: ") % negative % ";}" % ui.kIncome->styleSheet();
    m_neutralStyleSheet = QString(" QProgressBar { text-align: center; padding: 0.5px;} QProgressBar::chunk {text-align: center; border-radius:4px; background-color: ") % neutral % ";}" % ui.kIncome->styleSheet();
    m_positiveStyleSheet = QString(" QProgressBar { text-align: center; padding: 0.5px;} QProgressBar::chunk {text-align: center; border-radius:4px; background-color: ") % positive % ";}" % ui.kIncome->styleSheet();

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

    m_menuTransfert = new KAction(i18nc("Noun, a type of account", "Transfers"), this);
    m_menuTransfert->setCheckable(true);
    m_menuTransfert->setChecked(true);
    connect(m_menuTransfert, SIGNAL(triggered(bool)), this, SLOT(dataModified()));
    addAction(m_menuTransfert);

    //Refresh
    connect((const QObject*) getDocument(), SIGNAL(tableModified(QString,int)), this, SLOT(dataModified(QString,int)), Qt::QueuedConnection);
}

SKGOperationBoardWidget::~SKGOperationBoardWidget()
{
    SKGTRACEIN(10, "SKGOperationBoardWidget::~SKGOperationBoardWidget");
    m_menuTransfert = NULL;
}

QString SKGOperationBoardWidget::getState()
{
    QDomDocument doc("SKGML");
    QDomElement root = doc.createElement("parameters");
    doc.appendChild(root);

    root.setAttribute("menuTransfert", m_menuTransfert && m_menuTransfert->isChecked() ? "Y" : "N");
    return doc.toString();
}

void SKGOperationBoardWidget::setState(const QString& iState)
{
    QDomDocument doc("SKGML");
    doc.setContent(iState);
    QDomElement root = doc.documentElement();
    if (m_menuTransfert) m_menuTransfert->setChecked(root.attribute("menuTransfert") != "N");

    dataModified("", 0);
}

void SKGOperationBoardWidget::onOpen(const QString& iLink)
{
    //Call operation plugin
    QDomDocument doc("SKGML");

    //Get month
    QString wc;
    if (iLink.endsWith(QLatin1String("C"))) wc = "d_DATEMONTH=STRFTIME('%Y-%m', date('now'))";
    else wc = "d_DATEMONTH=STRFTIME('%Y-%m', date('now','-1 Month'))";

    if (iLink.startsWith(QLatin1String("I"))) wc = wc % " AND t_TYPEEXPENSE='+'";
    else wc = wc % " AND t_TYPEEXPENSE='-'";

    wc = wc % (m_menuTransfert && m_menuTransfert->isChecked() ? "" : " AND t_TRANSFER='N'");

    doc.setContent(getDocument()->getParameter("SKGOPERATION_DEFAULT_PARAMETERS"));
    QDomElement root = doc.documentElement();
    if (root.isNull()) {
        root = doc.createElement("parameters");
        doc.appendChild(root);
    }
    QString title;
    if (iLink == "IC") title = i18nc("Title of a list of operations", "Incomes of current month");
    else if (iLink == "EC") title = i18nc("Title of a list of operations", "Expenses of current month");
    else if (iLink == "IP") title = i18nc("Title of a list of operations", "Incomes of previous month");
    else if (iLink == "EP") title = i18nc("Title of a list of operations", "Expenses of previous month");

    root.setAttribute("operationWhereClause", wc);
    root.setAttribute("title", title);
    root.setAttribute("title_icon", "view-financial-list");
    root.setAttribute("currentPage", "-1");

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

void SKGOperationBoardWidget::dataModified(const QString& iTableName, int iIdTransaction)
{
    SKGTRACEIN(10, "SKGOperationBoardWidget::dataModified");
    Q_UNUSED(iIdTransaction);
    if (iTableName == "v_operation_display" || iTableName.isEmpty()) {
        //Get month
        QDate date = QDate::currentDate();
        date = date.addDays(1 - date.day());
        QDate date1 = date.addDays(-1);
        QString month = date.toString("yyyy-MM");
        QString previousmonth = date1.toString("yyyy-MM");

        SKGDocumentBank* doc = qobject_cast<SKGDocumentBank*>(getDocument());
        if (doc) {

            SKGServices::SKGUnitInfo primary = doc->getPrimaryUnit();
            SKGServices::SKGUnitInfo secondary = doc->getSecondaryUnit();

            SKGStringListList listTmp;
            SKGError err = getDocument()->executeSelectSqliteOrder(
                               "SELECT TOTAL(f_CURRENTAMOUNT), d_DATEMONTH  from v_operation_display WHERE d_DATEMONTH IN ('" % month % "', '" % previousmonth % "') " % (m_menuTransfert && m_menuTransfert->isChecked() ? "" : "AND t_TRANSFER='N'") % " group by d_DATEMONTH, t_TYPEEXPENSE",
                               listTmp);
            if (!err) {
                double income_previous_month = 0;
                double expense_previous_month = 0;
                double income_month = 0;
                double expense_month = 0;

                int nbval = listTmp.count();
                for (int i = 1; i < nbval; ++i) { //Ignore header
                    QString m = listTmp.at(i).at(1);
                    double v = SKGServices::stringToDouble(listTmp.at(i).at(0));
                    if (v > 0 && m == month) income_month = v;
                    else if (v < 0 && m == month) expense_month = -v;
                    else if (v > 0 && m == previousmonth) income_previous_month = v;
                    else if (v < 0 && m == previousmonth) expense_previous_month = -v;
                }

                //Set Maximum
                int max = qMax(income_previous_month, qMax(expense_previous_month, qMax(income_month, expense_month)));
                if (nbval == 1) max = 100.0;
                ui.kIncome->setMaximum(max);
                ui.kIncome_previous->setMaximum(max);
                ui.kExpense->setMaximum(max);
                ui.kExpense_previous->setMaximum(max);
                ui.kSaving->setMaximum(max);
                ui.kSaving_previous->setMaximum(max);

                //Set values
                ui.kIncome->setValue(income_month);
                ui.kIncome_previous->setValue(income_previous_month);
                ui.kExpense->setValue(expense_month);
                ui.kExpense_previous->setValue(expense_previous_month);
                ui.kSaving->setValue(qAbs(income_month - expense_month));
                ui.kSaving_previous->setValue(qAbs(income_previous_month - expense_previous_month));

                //Set texts and tool tips
                ui.kIncome->setFormat(doc->formatMoney(income_month, primary, false));
                ui.kIncome_previous->setFormat(doc->formatMoney(income_previous_month, primary, false));
                ui.kExpense->setFormat(doc->formatMoney(expense_month, primary, false));
                ui.kExpense_previous->setFormat(doc->formatMoney(expense_previous_month, primary, false));
                ui.kSaving->setFormat(doc->formatMoney(income_month - expense_month, primary, false));
                ui.kSaving_previous->setFormat(doc->formatMoney(income_previous_month - expense_previous_month, primary, false));
                if (!secondary.Symbol.isEmpty() && secondary.Value) {
                    ui.kIncome->setToolTip(doc->formatMoney(income_month, secondary, false));
                    ui.kIncome_previous->setToolTip(doc->formatMoney(income_previous_month, secondary, false));
                    ui.kExpense->setToolTip(doc->formatMoney(expense_month, secondary, false));
                    ui.kExpense_previous->setToolTip(doc->formatMoney(expense_previous_month, secondary, false));
                    ui.kSaving->setToolTip(doc->formatMoney(income_month - expense_month, secondary, false));
                    ui.kSaving_previous->setToolTip(doc->formatMoney(income_previous_month - expense_previous_month, secondary, false));
                }

                //Change colors
                ui.kIncome->setStyleSheet(m_positiveStyleSheet);
                ui.kIncome_previous->setStyleSheet(m_positiveStyleSheet);
                ui.kExpense->setStyleSheet(m_negativeStyleSheet);
                ui.kExpense_previous->setStyleSheet(m_negativeStyleSheet);
                ui.kSaving->setStyleSheet(income_month - expense_month < 0 ? m_negativeStyleSheet : income_month - expense_month < 0.1 * income_month ? m_neutralStyleSheet : m_positiveStyleSheet);
                ui.kSaving_previous->setStyleSheet(income_previous_month - expense_previous_month < 0 ? m_negativeStyleSheet : income_previous_month - expense_previous_month < 0.1 * income_previous_month ? m_neutralStyleSheet : m_positiveStyleSheet);
            }

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

#include "skgoperationboardwidget.moc"
