/***************************************************************************
 *   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 bank management.
 *
 * @author Stephane MANKOWSKI / Guillaume DE BURE
 */
#include "skgalarmboardwidget.h"
#include "skgdocumentbank.h"
#include "skgtraces.h"
#include "skgservices.h"
#include "skgaccountobject.h"
#include "skgunitobject.h"
#include "skgmainpanel.h"
#include "skgruleobject.h"

#include <kaction.h>

#include <QDomDocument>
#include <QProgressBar>
#include <kcolorscheme.h>

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

    ui.setupUi(this);

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

    m_menuFavorite = new KAction(KIcon("rating"), i18nc("Noun, an option in contextual menu", "Highlighted only"), this);
    m_menuFavorite->setCheckable(true);
    m_menuFavorite->setChecked(false);
    connect(m_menuFavorite, SIGNAL(triggered(bool)), this, SLOT(dataModified()));
    addAction(m_menuFavorite);

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

SKGAlarmBoardWidget::~SKGAlarmBoardWidget()
{
    SKGTRACEIN(10, "SKGAlarmBoardWidget::~SKGAlarmBoardWidget");

    m_menuFavorite = NULL;
}

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

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

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

    if (m_menuFavorite) m_menuFavorite->setChecked(root.attribute("menuFavorite") == "Y");

    dataModified("", 0);
}

void SKGAlarmBoardWidget::dataModified(const QString& iTableName, int iIdTransaction)
{
    SKGTRACEIN(10, "SKGAlarmBoardWidget::dataModified");
    Q_UNUSED(iIdTransaction);

    if (iTableName == "operation" || iTableName == "rule" || iTableName.isEmpty()) {
        //Remove all item of the layout
        QLayoutItem* child = NULL;
        while ((child = ui.layout->takeAt(0)) != 0) {
            QWidget* w = child->widget();
            delete w;
            delete child;
        }

        //Fill layout
        SKGDocumentBank* doc = qobject_cast<SKGDocumentBank*>(getDocument());
        if (doc) {
            SKGServices::SKGUnitInfo primary = doc->getPrimaryUnit();
            SKGServices::SKGUnitInfo secondary = doc->getSecondaryUnit();

            //Build where clause
            QString wc = "t_action_type='A'";
            if (m_menuFavorite && m_menuFavorite->isChecked()) {
                wc = "t_bookmarked='Y' AND (" % wc % ')';
            }

            SKGObjectBase::SKGListSKGObjectBase rules;
            SKGError err = doc->getObjects("v_rule", wc % " ORDER BY i_ORDER", rules);
            int nb = rules.count();
            if (nb) {
                //Get std colors
                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();

                for (int i = 0; !err && i < nb; ++i) {
                    SKGRuleObject rule = rules.at(i);
                    SKGRuleObject::SKGAlarmInfo alarm = rule.getAlarmInfo();

                    //Create progress bar
                    QProgressBar* progressBar = new QProgressBar(ui.kGroup);
                    progressBar->setObjectName(QString::fromUtf8("progressBar"));
                    progressBar->setMaximum(qMax(alarm.Amount, alarm.Limit));
                    progressBar->setValue(alarm.Amount);

                    QSizePolicy sizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed);
                    sizePolicy.setHorizontalStretch(0);
                    sizePolicy.setVerticalStretch(0);
                    sizePolicy.setHeightForWidth(progressBar->sizePolicy().hasHeightForWidth());
                    progressBar->setSizePolicy(sizePolicy);

                    //Set tooltip
                    QString txt = alarm.Message % "<br>";
                    txt += doc->formatMoney(alarm.Amount, primary) % " / " % doc->formatMoney(alarm.Limit, primary);
                    if (!secondary.Symbol.isEmpty() && secondary.Value) {
                        txt += "<br>" % doc->formatMoney(alarm.Amount, secondary) % " / " % doc->formatMoney(alarm.Limit, secondary);
                    }
                    progressBar->setToolTip(txt);

                    //Change color
                    double percent = 100 * alarm.Amount / alarm.Limit;
                    QString st = progressBar->styleSheet();
                    st = QString(" QProgressBar { text-align: center; padding: 0.5px;} QProgressBar::chunk {text-align: center; border-radius:4px; background-color: ") % (percent < 70 ? positive : (percent > 90 ? negative : neutral)) % ";}" % st;
                    progressBar->setStyleSheet(st);

                    //Add progress bar
                    ui.layout->addWidget(progressBar);
                }
            } else {
                QLabel* lab = new QLabel(ui.kGroup);
                lab->setTextInteractionFlags(Qt::LinksAccessibleByMouse | Qt::TextSelectableByMouse);
                lab->setText(i18nc("Message", "No alarm defined<br>on the <a href=\"___\">\"Search and process\"</a> page."));
                connect(lab, SIGNAL(linkActivated(QString)), this, SLOT(onOpen(QString)));

                //Add progress bar
                ui.layout->addWidget(lab);
            }

            //Add spacer
            ui.layout->addItem(new QSpacerItem(20, 40, QSizePolicy::Minimum, QSizePolicy::Expanding));

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

void SKGAlarmBoardWidget::onOpen(const QString& iLink)
{
    ui.kGroup->setChecked(true);

    QDomDocument doc("SKGML");
    if (iLink == "___") {
        doc.setContent(getDocument()->getParameter("SKGSEARCH_DEFAULT_PARAMETERS"));
        SKGMainPanel::getMainPanel()->openPage(SKGMainPanel::getMainPanel()->getPluginByName("Skrooge search plugin"), -1, doc.toString());
    }
}

#include "skgalarmboardwidget.moc"
