/***************************************************************************
 *   Copyright (C) 2020 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 impgnced 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 <https://www.gnu.org/licenses/>  *
 ***************************************************************************/
/** @file
 * This file is Skrooge plugin for JSON import / export.
 *
 * @author Stephane MANKOWSKI / Guillaume DE BURE
 */
#include "skgimportpluginjson.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(SKGImportPluginJsonFactory, registerPlugin<SKGImportPluginJson>();)

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

SKGImportPluginJson::~SKGImportPluginJson()
    = default;

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

SKGError SKGImportPluginJson::exportFile()
{
    SKGError err;
    QString doc;
    err = m_importer->getDocument()->copyToJson(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 << SKGENDL;

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

QString SKGImportPluginJson::getMimeTypeFilter() const
{
    return "*.json|" % i18nc("A file format", "JSON file");
}

#include <skgimportpluginjson.moc>
