/***************************************************************************
 * SPDX-FileCopyrightText: 2022 S. MANKOWSKI stephane@mankowski.fr
 * SPDX-FileCopyrightText: 2022 G. DE BURE support@mankowski.fr
 * SPDX-License-Identifier: GPL-3.0-or-later
 ***************************************************************************/
/** @file
 * This file is Skrooge plugin for XML import / export.
 *
 * @author Stephane MANKOWSKI / Guillaume DE BURE
 */
#include "skgimportpluginxml.h"

#include <klocalizedstring.h>
#include <kpluginfactory.h>

#include <qsavefile.h>

#include "skgdocumentbank.h"
#include "skgservices.h"
#include "skgtraces.h"

/**
 * This plugin factory.
 */
K_PLUGIN_FACTORY(SKGImportPluginXmlFactory, registerPlugin<SKGImportPluginXml>();)

SKGImportPluginXml::SKGImportPluginXml(QObject* iImporter, const QVariantList& iArg)
    : SKGImportPlugin(iImporter)
{
    SKGTRACEINFUNC(10)
    Q_UNUSED(iArg)
}

SKGImportPluginXml::~SKGImportPluginXml()
    = default;

bool SKGImportPluginXml::isExportPossible()
{
    SKGTRACEINFUNC(10)
    return (m_importer == nullptr ? true : m_importer->getFileNameExtension() == QStringLiteral("XML"));
}

SKGError SKGImportPluginXml::exportFile()
{
    SKGError err;
    QDomDocument doc;
    err = SKGServices::copySqliteDatabaseToXml(*(m_importer->getDocument()->getMainDatabase()), doc);
    IFOK(err) {
        QSaveFile file(m_importer->getLocalFileName(false));
        if (!file.open(QIODevice::WriteOnly)) {
            err.setReturnCode(ERR_INVALIDARG).setMessage(i18nc("Error message",  "Save file '%1' failed", m_importer->getFileName().toDisplayString()));
        } else {
            QTextStream stream(&file);
            if (!m_importer->getCodec().isEmpty()) {
                stream.setCodec(m_importer->getCodec().toLatin1().constData());
            }
            stream << doc.toString() << SKGENDL;

            // Close file
            file.commit();
        }
    }
    return err;
}

QString SKGImportPluginXml::getMimeTypeFilter() const
{
    return "*.xml|" % i18nc("A file format", "XML file");
}

#include <skgimportpluginxml.moc>
