/***************************************************************************
 *   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
 * A plugin for monthly report
 *
 * @author Stephane MANKOWSKI
 */
#include "skgmonthlyplugin.h"

#include <kactioncollection.h>
#include <kstandardaction.h>
#include <kaboutdata.h>
#include <kcolorscheme.h>
#include <kpluginfactory.h>
#include <klocalizedstring.h>

#include <qdesktopservices.h>
#include <qfileinfo.h>
#include <qdir.h>
#include <qfile.h>
#include <qstandardpaths.h>
#include <qdiriterator.h>

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

/**
 * This plugin factory.
 */
K_PLUGIN_FACTORY(SKGMonthlyPluginFactory, registerPlugin<SKGMonthlyPlugin>();)

SKGMonthlyPlugin::SKGMonthlyPlugin(QWidget* iWidget, QObject* iParent, const QVariantList& /*iArg*/) :
    SKGInterfacePlugin(iParent),
    m_currentBankDocument(nullptr), m_mainPage(nullptr)
{
    Q_UNUSED(iWidget);
    SKGTRACEINFUNC(10);
}

SKGMonthlyPlugin::~SKGMonthlyPlugin()
{
    SKGTRACEINFUNC(10);
    m_currentBankDocument = nullptr;
}

bool SKGMonthlyPlugin::setupActions(SKGDocument* iDocument, const QStringList& iArgument)
{
    SKGTRACEINFUNC(10);
    Q_UNUSED(iArgument);
    m_currentBankDocument = iDocument;

    setComponentName(QStringLiteral("skg_monthly"), title());
    setXMLFile(QStringLiteral("skg_monthly.rc"));

    KColorScheme scheme(QPalette::Normal, KColorScheme::Window);

    // Initialise the main page
#ifdef SKG_WEBENGINE
    {
        SKGTRACEIN(10, "SKGMonthlyPlugin::setupActions-Init SKGWebView");
        m_mainPage = new SKGWebView(SKGMainPanel::getMainPanel(), 0, false);
        SKGMainPanel::getMainPanel()->setMainWidget(m_mainPage);
        refreshMainPage();
        connect(m_currentBankDocument, &SKGDocument::transactionSuccessfullyEnded, this, &SKGMonthlyPlugin::refreshMainPage);
        qApp->processEvents(QEventLoop::AllEvents, 500);
    }
#else
    m_mainPage = new QWebView();
    m_mainPage->page()->setLinkDelegationPolicy(QWebPage::DelegateAllLinks);
    connect(m_mainPage, &QWebView::linkClicked, this, [ = ](const QUrl & val) {
        SKGMainPanel::getMainPanel()->openPage(val);
    });
    SKGMainPanel::getMainPanel()->setMainWidget(m_mainPage);
    refreshMainPage();
    connect(m_currentBankDocument, &SKGDocument::transactionSuccessfullyEnded, this, &SKGMonthlyPlugin::refreshMainPage);
#endif

    // Make needed paths
    QString writablePath = QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation);
    QString path = writablePath % QLatin1Char('/') + KAboutData::applicationData().componentName() % QStringLiteral("/html/default");
    if (!QDir(writablePath).mkpath(KAboutData::applicationData().componentName() % QStringLiteral("/html/default"))) {
        SKGTRACE << "WARNING: Impossible to create  html/default in " << writablePath << endl;
    }

    // Copy "default" directory in locale
    const auto dirs = QStandardPaths::locateAll(QStandardPaths::GenericDataLocation, KAboutData::applicationData().componentName() % "/html/default", QStandardPaths::LocateDirectory);
    for (const auto& dir : dirs) {
        QDirIterator it(dir, QStringList() << QStringLiteral("*.html"));
        while (it.hasNext()) {
            QString file = it.next();

            QString target = path % QLatin1Char('/') % QFileInfo(file).fileName();
            QFile(target).remove();
            if (file != target && !QFile(file).copy(target)) {
                SKGTRACE << "WARNING: Impossible to copie " << file << " in " << target << endl;
            }
        }
    }

    // Create yours actions here
    return true;
}

void SKGMonthlyPlugin::refreshMainPage()
{
    QString html;

    QString templateFile = QStandardPaths::locate(QStandardPaths::GenericDataLocation, KAboutData::applicationData().componentName() % "/html/main.txt");
    if (templateFile.isEmpty()) {
        html = i18nc("Error message", "File %1/html/main.txt not found", KAboutData::applicationData().componentName());
    } else {
        if (m_currentBankDocument) {
            SKGReport* rep = m_currentBankDocument->getReport();
            SKGError err = rep->getReportFromTemplate(rep, templateFile, html);
            IFKO(err) html += err.getFullMessageWithHistorical();
            delete rep;
        }
    }
#ifdef SKG_WEBENGINE
    m_mainPage->setHtml(html, QUrl("file://"));
#else
    m_mainPage->setHtml(html);
#endif
}

SKGTabPage* SKGMonthlyPlugin::getWidget()
{
    SKGTRACEINFUNC(10);
    return new SKGMonthlyPluginWidget(SKGMainPanel::getMainPanel(), m_currentBankDocument);
}

QString SKGMonthlyPlugin::title() const
{
    return toolTip();
}

QString SKGMonthlyPlugin::icon() const
{
    return QStringLiteral("view-calendar-journal");
}

QString SKGMonthlyPlugin::toolTip() const
{
    return i18nc("A tool tip", "Monthly report");
}

int SKGMonthlyPlugin::getOrder() const
{
    return 50;
}

QStringList SKGMonthlyPlugin::tips() const
{
    QStringList output;
    output.push_back(i18nc("Description of a tips", "<p>... you can generate a monthly report.</p>"));
    output.push_back(i18nc("Description of a tips", "<p>... you can download more monthly report templates.</p>"));
    output.push_back(i18nc("Description of a tips", "<p>... you can create and share your own monthly report template.</p>"));
    return output;
}

bool SKGMonthlyPlugin::isInPagesChooser() const
{
    return true;
}

#include <skgmonthlyplugin.moc>
