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

#include "skgdocumentbank.h"
#include "skgtraces.h"
#include "skgunitobject.h"
#include "skgmainpanel.h"

SKGUnitBoardWidget::SKGUnitBoardWidget(SKGDocument* iDocument)
    : SKGBoardWidget(iDocument, i18nc("Title of a dashboard widget", "Quotes"))
{
    SKGTRACEINFUNC(10);

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

    m_menuFavorite = new QAction(QIcon::fromTheme("bookmarks"), i18nc("Display only favorite accounts", "Highlighted only"), this);
    m_menuFavorite->setCheckable(true);
    m_menuFavorite->setChecked(false);
    connect(m_menuFavorite, &QAction::triggered, [ = ]() {
        this->dataModified();
    });
    addAction(m_menuFavorite);

    {
        QAction* sep = new QAction(this);
        sep->setSeparator(true);
        addAction(sep);
    }

    m_menuCurrencies = new QAction(i18nc("Noun, a country's currency", "Currencies"), this);
    m_menuCurrencies->setCheckable(true);
    m_menuCurrencies->setChecked(true);
    connect(m_menuCurrencies, &QAction::triggered, [ = ]() {
        this->dataModified();
    });
    addAction(m_menuCurrencies);

    m_menuIndexes = new QAction(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, &QAction::triggered, [ = ]() {
        this->dataModified();
    });
    addAction(m_menuIndexes);

    m_menuShares = new QAction(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, &QAction::triggered, [ = ]() {
        this->dataModified();
    });
    addAction(m_menuShares);

    m_menuObjects = new QAction(i18nc("Noun, a physical object like a house or a car", "Objects"), this);
    m_menuObjects->setCheckable(true);
    m_menuObjects->setChecked(true);
    connect(m_menuObjects, &QAction::triggered, [ = ]() {
        this->dataModified();
    });
    addAction(m_menuObjects);

    m_menuSharesOwnedOnly = new QAction(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, &QAction::triggered, [ = ]() {
        this->dataModified();
    });
    addAction(m_menuSharesOwnedOnly);

    m_label = new QLabel();
    setMainWidget(m_label);

    // Refresh
    connect(getDocument(), &SKGDocument::tableModified, this, &SKGUnitBoardWidget::dataModified, Qt::QueuedConnection);
    connect(m_label, &QLabel::linkActivated, [ = ](const QString & val) {
        SKGMainPanel::getMainPanel()->openPage(val);
    });
}

SKGUnitBoardWidget::~SKGUnitBoardWidget()
{
    SKGTRACEINFUNC(10);
    m_menuIndexes = NULL;
    m_menuShares = NULL;
    m_menuSharesOwnedOnly = NULL;
    m_menuObjects = NULL;
    m_menuCurrencies = NULL;
    m_menuFavorite = NULL;
}

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

    root.setAttribute("m_menuCurrencies", m_menuCurrencies && m_menuCurrencies->isChecked() ? "Y" : "N");
    root.setAttribute("m_menuObjects", m_menuObjects && m_menuObjects->isChecked() ? "Y" : "N");
    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");
    root.setAttribute("menuFavorite", m_menuFavorite && m_menuFavorite->isChecked() ? "Y" : "N");
    return doc.toString();
}

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

    if (m_menuCurrencies) {
        m_menuCurrencies->setChecked(root.attribute("m_menuCurrencies") == "Y");
    }
    if (m_menuObjects) {
        m_menuObjects->setChecked(root.attribute("m_menuObjects") == "Y");
    }
    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");
    }
    if (m_menuFavorite) {
        m_menuFavorite->setChecked(root.attribute("menuFavorite") == "Y");
    }

    dataModified("", 0);
}

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

    if (iTableName == "v_unit_display" || iTableName.isEmpty()) {
        SKGDocumentBank* doc = qobject_cast<SKGDocumentBank*>(getDocument());
        if (doc) {
            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 (m_menuCurrencies->isChecked()) {
                    if (!wc.isEmpty()) {
                        wc += " OR ";
                    }
                    wc += "t_type IN ('1','2','C')";
                }
                if (m_menuObjects->isChecked()) {
                    if (!wc.isEmpty()) {
                        wc += " OR ";
                    }
                    wc += "t_type='O'";
                }
            }

            if (wc.isEmpty()) {
                wc = "1=0";
            } else if (m_menuFavorite && m_menuFavorite->isChecked()) {
                wc = "t_bookmarked='Y' AND (" % wc % ')';
            }

            SKGObjectBase::SKGListSKGObjectBase objs;
            SKGError err = getDocument()->getObjects("v_unit_display", wc % " ORDER BY t_type DESC, t_name ASC", objs);
            IFOK(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=\"skg://Skrooge_operation_plugin/?operationWhereClause=rc_unit_id=" % SKGServices::intToString(obj.getID()) %
                                        "&title=" % SKGServices::encodeForUrl(i18nc("A list of operations made on the specified unit", "Operations with unit equal to '%1'",  obj.getName())) %
                                        "&title_icon=taxes-finances&currentPage=-1" % "\">") % 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=\"%1\">\"Units\"</a> page.", "skg://Skrooge_unit_plugin");
                }
                html += "</body></html>";
                m_label->setText(html);
            }

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


