/***************************************************************************
 *   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 <qwidgetaction.h>
#include <QDomDocument>

#include <klocalizedstring.h>

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

SKGHtmlBoardWidget::SKGHtmlBoardWidget(SKGDocument* iDocument, const QString& iTitle, const QString& iTemplate, const QStringList& iTablesRefreshing, AdditionalOption iOptions)
    : SKGBoardWidget(iDocument, iTitle), m_HtmlTemplate(iTemplate), m_TablesRefreshing(iTablesRefreshing), m_refreshNeeded(false), m_period(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 (iOptions == PERIOD_ONLY_MONTHS || iOptions == PERIOD_ALL) {
        setContextMenuPolicy(Qt::ActionsContextMenu);

        m_period = new SKGSimplePeriodEdit(this);
        m_period->setMode(iOptions == PERIOD_ONLY_MONTHS ? SKGSimplePeriodEdit::PREVIOUS_AND_CURRENT_MONTHS : SKGSimplePeriodEdit::PREVIOUS_AND_CURRENT_PERIODS);

        QDate date = QDate::currentDate();
        QStringList list;
        // TODO(Stephane MANKOWSKI): v_operation_display must be generic
        getDocument()->getDistinctValues("v_operation_display", "MIN(d_DATEMONTH)", "d_date<=CURRENT_DATE", list);
        if (list.count()) {
            if (!list[0].isEmpty()) {
                date = SKGServices::periodToDate(list[0]);
            }
        }
        m_period->setFirstDate(date);

        QWidgetAction* periodEditWidget = new QWidgetAction(this);
        periodEditWidget->setDefaultWidget(m_period);

        addAction(periodEditWidget);

        connect(m_period, static_cast<void (SKGComboBox::*)(const QString&)>(&SKGComboBox::currentIndexChanged), [ = ]() {
            this->dataModified();
        });
    }

    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_period = NULL;
}

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

    // Get state
    if (m_period) {
        root.setAttribute("period", m_period->text());
    }

    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_period) {
        QString oldMode = root.attribute("previousMonth");
        if (oldMode.isEmpty()) {
            QString period = root.attribute("period");
            if (!period.isEmpty()) {
                m_period->setText(period);
            }
        } else {
            m_period->setText(oldMode == "N" ? i18nc("The current month", "Current month") : i18nc("The month before the current month", "Last month"));
        }
    }

    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
            QString period = (m_period ? m_period->period() : SKGServices::dateToPeriod(QDate::currentDate(), "M"));

            // Set title
            setMainTitle(getOriginalTitle() % (m_period ? QString(" - ") % period : QString("")));

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

            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"
