/***************************************************************************
 *   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 <KAction>

#include <QDomDocument>

#include "skgdocumentbank.h"
#include "skgtraces.h"
#include "skgservices.h"
#include "skgaccountobject.h"
#include "skgunitobject.h"
#include "skgmainpanel.h"
#include "skgruleobject.h"
#include "skgprogressbar.h"

SKGAlarmBoardWidget::SKGAlarmBoardWidget(SKGDocument* iDocument)
    : SKGBoardWidget(iDocument, i18nc("Dashboard widget title", "Alarms"))
{
    SKGTRACEINFUNC(10);

    // Create widget
    m_frame = new QFrame();
    m_layout = new QVBoxLayout(m_frame);
    m_layout->setSpacing(2);
    m_layout->setContentsMargins(0, 0, 0, 0);
    setMainWidget(m_frame);

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

    KAction* open = new KAction(KIcon("skg_open"), i18nc("Verb, open a page", "Open..."), this);
    open->setData("skg://skrooge_search_plugin");
    connect(open, SIGNAL(triggered(bool)), SKGMainPanel::getMainPanel(), SLOT(openPage()));
    addAction(open);

    m_menuFavorite = new KAction(KIcon("bookmarks"), 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(getDocument(), SIGNAL(tableModified(QString,int,bool)), this, SLOT(dataModified(QString,int)), Qt::QueuedConnection);
}

SKGAlarmBoardWidget::~SKGAlarmBoardWidget()
{
    SKGTRACEINFUNC(10);

    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)
{
    SKGTRACEINFUNC(10);
    Q_UNUSED(iIdTransaction);

    if (iTableName == "operation" || iTableName == "rule" || iTableName.isEmpty()) {
        // Remove all item of the layout
        while (m_layout->count()) {
            QLayoutItem* child = m_layout->takeAt(0);
            if (child) {
                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) {
                for (int i = 0; !err && i < nb; ++i) {
                    SKGRuleObject rule(rules.at(i));
                    SKGRuleObject::SKGAlarmInfo alarm = rule.getAlarmInfo();

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

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

                    // 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
                    progressBar->setLimits(qMax(alarm.Amount, alarm.Limit), 0.9 * alarm.Limit, 0.7 * alarm.Limit);

                    // Add progress bar
                    m_layout->addWidget(progressBar);
                }
            } else {
                QLabel* lab = new QLabel(m_frame);
                lab->setTextInteractionFlags(Qt::LinksAccessibleByMouse | Qt::TextSelectableByMouse);
                lab->setText(i18nc("Message", "No alarm defined<br>on the <a href=\"%1\">\"Search and process\"</a> page.", "skg://Skrooge_search_plugin"));
                connect(lab, SIGNAL(linkActivated(QString)), SKGMainPanel::getMainPanel(), SLOT(openPage(QString)));

                // Add progress bar
                m_layout->addWidget(lab);
            }

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

#include "skgalarmboardwidget.moc"
