/***************************************************************************
 *   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 unit management.
 *
 * @author Stephane MANKOWSKI / Guillaume DE BURE
 */
#include "skgunitboardwidget.h"
#include "skgdocumentbank.h"
#include "skgtraces.h"
#include "skgunitobject.h"
#include "skgmainpanel.h"

#include <QDomDocument>

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

    ui.setupUi(this);

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

    m_menuIndexes = new KAction(i18nc("Financial indexes, used as an indicator of financial places' health. Examples : Dow Jones, CAC40, Nikkei...", "Indexes"), this);
    m_menuIndexes->setCheckable(true);
    m_menuIndexes->setChecked(true);
    connect(m_menuIndexes, SIGNAL(triggered(bool)), this, SLOT(dataModified()));
    addAction(m_menuIndexes);

    m_menuShares = new KAction(i18nc("Shares, as in financial shares: parts of a company that you can buy or sell on financial markets", "Shares"), this);
    m_menuShares->setCheckable(true);
    m_menuShares->setChecked(true);
    connect(m_menuShares, SIGNAL(triggered(bool)), this, SLOT(dataModified()));
    addAction(m_menuShares);

    m_menuSharesOwnedOnly = new KAction(i18nc("Only show the list of Shares (financial shares) that you own", "Shares owned only"), this);
    m_menuSharesOwnedOnly->setCheckable(true);
    m_menuSharesOwnedOnly->setChecked(false);
    connect(m_menuSharesOwnedOnly, SIGNAL(triggered(bool)), this, SLOT(dataModified()));
    addAction(m_menuSharesOwnedOnly);

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

SKGUnitBoardWidget::~SKGUnitBoardWidget()
{
    SKGTRACEIN(10, "SKGUnitBoardWidget::~SKGUnitBoardWidget");
    m_menuIndexes = NULL;
    m_menuShares = NULL;
    m_menuSharesOwnedOnly = NULL;
}

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

    root.setAttribute("menuIndexes", m_menuIndexes && m_menuIndexes->isChecked() ? "Y" : "N");
    root.setAttribute("menuShares", m_menuShares && m_menuShares->isChecked() ? "Y" : "N");
    root.setAttribute("menuSharesOwnedOnly", m_menuSharesOwnedOnly && m_menuSharesOwnedOnly->isChecked() ? "Y" : "N");
    return doc.toString();
}

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

    if (m_menuIndexes) m_menuIndexes->setChecked(root.attribute("menuIndexes") != "N");
    if (m_menuShares) m_menuShares->setChecked(root.attribute("menuShares") != "N");
    if (m_menuSharesOwnedOnly) m_menuSharesOwnedOnly->setChecked(root.attribute("menuSharesOwnedOnly") != "N");

    dataModified("", 0);
}

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

    if (iTableName == "unit" || iTableName.isEmpty()) {
        KLocale* locale = KGlobal::locale();
        SKGDocumentBank* doc = qobject_cast<SKGDocumentBank*>(getDocument());
        if (doc && locale) {
            SKGServices::SKGUnitInfo primary = doc->getPrimaryUnit();

            //Build where clause
            QString wc;
            if (m_menuSharesOwnedOnly && m_menuShares && m_menuIndexes) {
                m_menuSharesOwnedOnly->setEnabled(m_menuShares->isChecked());
                m_menuShares->setEnabled(!m_menuSharesOwnedOnly->isChecked());
                if (!m_menuShares->isChecked()) m_menuSharesOwnedOnly->setChecked(false);

                if (m_menuIndexes->isChecked()) {
                    wc = "t_type='I'";
                }
                if (m_menuShares->isChecked()) {
                    if (!wc.isEmpty()) wc += " OR ";
                    if (m_menuSharesOwnedOnly->isChecked()) wc += "(t_type='S' AND f_QUANTITYOWNED>0)";
                    else wc += "t_type='S'";
                }
            }

            if (wc.isEmpty()) wc = "1=0";

            SKGObjectBase::SKGListSKGObjectBase objs;
            SKGError err = getDocument()->getObjects("v_unit_display", wc % " ORDER BY t_type DESC, t_name ASC", objs);
            if (!err) {
                QString html;
                html += "<html><body>";
                int nb = objs.count();
                if (nb) {
                    html += "<table>";
                    QString lastTitle;
                    for (int i = 0; i < nb; ++i) {
                        SKGUnitObject obj = objs.at(i);
                        QString type = obj.getAttribute("t_TYPENLS");
                        if (lastTitle != type) {
                            lastTitle = type;
                            html += "<tr><td><b>" % SKGServices::stringToHtml(lastTitle) % "</b></td></tr>";
                        }
                        html += QString("<tr><td><a href=\"" % SKGServices::stringToHtml(obj.getSymbol()) % "\">") % SKGServices::stringToHtml(obj.getDisplayName()) % "</a></td><td align=\"right\">";
                        if (obj.getType() == SKGUnitObject::INDEX) primary.Symbol = ' ';
                        html += doc->formatMoney(SKGServices::stringToDouble(obj.getAttribute("f_CURRENTAMOUNT")), primary);
                        html += "</td><td>(";
                        double val = obj.getDailyChange();
                        html += doc->formatPercentage(val);
                        html += ")</td></tr>";
                    }
                    html += "</table>";
                } else {
                    html += i18nc("Message about not having any financial Share or financial index in the document", "No share or index defined<br>on the <a href=\"___\">\"Units\"</a> page.");
                }
                html += "</body></html>";
                ui.kLabel->setText(html);
            }

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

void SKGUnitBoardWidget::onOpen(const QString& iLink)
{
    QDomDocument doc("SKGML");
    if (iLink != "___") {
        SKGUnitObject unit(static_cast<SKGDocumentBank*>(getDocument()));
        unit.setSymbol(iLink);
        unit.load();
        int unitid = unit.getID();

        //Build where clause and title
        QString wc = "rc_unit_id=" % SKGServices::intToString(unitid);
        QString title = i18nc("A list of operations made on the specified unit", "Operations with unit equal to '%1'",  unit.getName());

        //Open
        //Call operation plugin
        doc.setContent(getDocument()->getParameter("SKGOPERATION_DEFAULT_PARAMETERS"));
        QDomElement root = doc.documentElement();
        if (root.isNull()) {
            root = doc.createElement("parameters");
            doc.appendChild(root);
        }

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

        SKGMainPanel::getMainPanel()->openPage(SKGMainPanel::getMainPanel()->getPluginByName("Skrooge operation plugin"), -1, doc.toString());
    } else {
        doc.setContent(getDocument()->getParameter("SKGUNIT_DEFAULT_PARAMETERS"));
        SKGMainPanel::getMainPanel()->openPage(SKGMainPanel::getMainPanel()->getPluginByName("Skrooge unit plugin"), -1, doc.toString());
    }
}
#include "skgunitboardwidget.moc"
