/***************************************************************************
 *   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 a generic Skrooge plugin for html reports.
 *
 * @author Stephane MANKOWSKI / Guillaume DE BURE
 */
#include "skghtmlboardwidget.h"

#include <qtoolbutton.h>

#include <klocalizedstring.h>
#include <QDomDocument>

#include "skgdocument.h"
#include "skgtraces.h"
#include "skgreport.h"
#include "skgmainpanel.h"

SKGHtmlBoardWidget::SKGHtmlBoardWidget(SKGDocument* iDocument, const QString& iTitle, const QString& iTemplate, const QStringList& iTablesRefreshing, bool iEnablePreviousMenu)
    : SKGBoardWidget(iDocument, iTitle), m_HtmlTemplate(iTemplate), m_TablesRefreshing(iTablesRefreshing), m_refreshNeeded(false), m_previousMonth(NULL)
{
    SKGTRACEINFUNC(10);

    m_Text = new QLabel();
    m_Text->setObjectName(QString::fromUtf8("m_Text"));
    m_Text->setTextFormat(Qt::RichText);
    m_Text->setAlignment(Qt::AlignLeading | Qt::AlignLeft | Qt::AlignTop);
    m_Text->setTextInteractionFlags(Qt::TextBrowserInteraction);

    setMainWidget(m_Text);

    // Create menu
    if (iEnablePreviousMenu) {
        setContextMenuPolicy(Qt::ActionsContextMenu);
        m_previousMonth = new QAction(i18nc("Report for the previous month", "Previous month"), this);
        m_previousMonth->setCheckable(true);
        m_previousMonth->setChecked(true);
        connect(m_previousMonth, &QAction::triggered, [ = ]() {
            this->dataModified();
        });
        addAction(m_previousMonth);
    }

    connect(getDocument(), &SKGDocument::tableModified, this, &SKGHtmlBoardWidget::dataModified, Qt::QueuedConnection);
    connect(SKGMainPanel::getMainPanel(), &SKGMainPanel::currentPageChanged, this, &SKGHtmlBoardWidget::pageChanged, Qt::QueuedConnection);
    connect(m_Text, &QLabel::linkActivated, [ = ](const QString & val) {
        SKGMainPanel::getMainPanel()->openPage(val);
    });
}

SKGHtmlBoardWidget::~SKGHtmlBoardWidget()
{
    SKGTRACEINFUNC(10);
    m_previousMonth = NULL;
}

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

    // Get state
    root.setAttribute("previousMonth", m_previousMonth && m_previousMonth->isChecked() ? "Y" : "N");

    return doc.toString();
}

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

    // Set state
    if (m_previousMonth) {
        m_previousMonth->setChecked(root.attribute("previousMonth") != "N");
    }

    dataModified("", 0);
}

void SKGHtmlBoardWidget::pageChanged()
{
    if (m_refreshNeeded) {
        dataModified();
    }
}

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

    if (m_TablesRefreshing.isEmpty() || m_TablesRefreshing.contains(iTableName) || iTableName.isEmpty()) {
        // Is this the current page
        SKGTabPage* page = SKGTabPage::parentTabPage(this);
        if (page != NULL && page != SKGMainPanel::getMainPanel()->currentPage()) {
            // No, we memorize that we have to cumpute later the report
            m_refreshNeeded = true;
            return;
        }
        QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));

        // Computation of the report
        SKGReport* report = getDocument()->getReport();
        if (report) {
            // Compute parameters
            QDate month = QDate::currentDate();
            month = month.addDays(-month.day() + 1);
            if (m_previousMonth) {
                if (m_previousMonth->isChecked()) {
                    month = month.addMonths(-1);
                }
            } else {
                // No mode "month" ==> we force to the infinite
                month = QDate(2999, 12, 31);
            }
            QString monthS = month.toString("yyyy-MM");

            // Set title
            setMainTitle(getOriginalTitle() % (m_previousMonth ? QString(" - ") % monthS : QString("")));

            // Set month
            report->setPeriod(monthS);

            QString html;
            SKGError err = SKGReport::getReportFromTemplate(report, m_HtmlTemplate, html);
            IFKO(err) html = err.getFullMessage();
            html = html.remove(QRegExp("<img[^>]*/>"));
            m_Text->setText(html);

            delete report;
        }
        m_refreshNeeded = false;

        QApplication::restoreOverrideCursor();
    }

    // TODO(Stephane MANKOWSKI): No widget if no account (must not be hardcoded)
    bool exist = false;
    getDocument()->existObjects("account", "", exist);
    if (parentWidget()) {
        setVisible(exist);
    }
}
#include "skghtmlboardwidget.h"
