/*****************************************************************************
 * $CAMITK_LICENCE_BEGIN$
 *
 * CamiTK - Computer Assisted Medical Intervention ToolKit
 * (c) 2001-2025 Univ. Grenoble Alpes, CNRS, Grenoble INP - UGA, TIMC, 38000 Grenoble, France
 *
 * Visit http://camitk.imag.fr for more information
 *
 * This file is part of CamiTK.
 *
 * CamiTK is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * CamiTK 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 Lesser General Public License version 3 for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with CamiTK.  If not, see <http://www.gnu.org/licenses/>.
 *
 * $CAMITK_LICENCE_END$
 ****************************************************************************/

#include "CamiTKExtensionModel.h"

#include <QJsonParseError>
#include <QJsonArray>
#include <QJsonObject>
#include <QFileInfo>

#include <iostream>

// -------------------- constructor --------------------
CamiTKExtensionModel::CamiTKExtensionModel(const QString& filePath) {
    extensions = VariantDataModel();
    if (!filePath.isNull()) {
        load(filePath);
    }
}

// -------------------- clear --------------------
void CamiTKExtensionModel::clear() {
    // empty model
    extensions = VariantDataModel();
}

// -------------------- getModel --------------------
VariantDataModel& CamiTKExtensionModel::getModel() {
    return extensions;
}

// -------------------- setModel --------------------
void CamiTKExtensionModel::setModel(VariantDataModel& newModel) {
    extensions = VariantDataModel(newModel);
}

// -------------------- toJSON --------------------
QString CamiTKExtensionModel::toJSON() {
    // rebuild file from config
    QVariantMap content = {};
    content["version"] = "camitk-6.0";
    content["timestamp"] = QDateTime::currentDateTime().toString(Qt::ISODate);
    content["extensions"] = extensions.getValue();

    QVariantMap fullContent = {{"camitk", content},};

    QJsonDocument jsonContent = QJsonDocument::fromVariant(fullContent);
    return jsonContent.toJson(QJsonDocument::Indented);
}

// -------------------- resetModel --------------------
void CamiTKExtensionModel::resetModel(QString extensionName) {
    extensions = VariantDataModel(QVariantMap());
    extensions.insert("name", extensionName[0].toUpper() + extensionName.right(extensionName.length() - 1));
    extensions.insert("license", "LGPL-3 CamiTK");
    QVariantList emptyList;
    // static_cast is required to avoid a
    // 'more than one instance of overloaded function "Foo::insert" matches the argument list'
    // compiler error (as there is also an insert(QString, VariantDataModel) that can be
    // called using the VariantDataModel(QVariantList) constructor)
    extensions.insert("actions", static_cast<QVariant>(emptyList));
    extensions.insert("components", static_cast<QVariant>(emptyList));
    extensions.insert("viewers", static_cast<QVariant>(emptyList));
    extensions.insert("libraries", static_cast<QVariant>(emptyList));
    extensions.insert("applications", static_cast<QVariant>(emptyList));
}

// -------------------- isModified --------------------
bool CamiTKExtensionModel::isModified() {
    return extensions.isModified();
}

// -------------------- load --------------------
bool CamiTKExtensionModel::load(const QString& filePath) {
    if (filePath.isEmpty()) {
        // reset the model
        clear();
        std::cerr << "load() called with an empty filename, CamiTKExtensionModel model was cleared." << "\n";
        return true;
    }

    QFile camitkFile;
    camitkFile.setFileName(filePath);

    if (!camitkFile.open(QIODevice::ReadOnly | QIODevice::Text)) {
        std::cerr << "Error opening .camitk JSON file " << filePath.toStdString() << ": " << camitkFile.errorString().toStdString() << "\n";
        return false;
    }

    QByteArray jsonData = camitkFile.readAll();
    camitkFile.close();

    QJsonParseError jsonParseError;
    QJsonDocument jsonDoc = QJsonDocument::fromJson(jsonData, &jsonParseError);
    if (jsonDoc.isNull()) {
        // extract the string from the error offset to the next return carriage
        QString jsonErrorData(jsonData.mid(jsonParseError.offset, jsonData.indexOf("\n", jsonParseError.offset) - jsonParseError.offset));
        int lineNr = jsonData.left(jsonParseError.offset).count('\n');
        if (lineNr == 0) {
            std::cerr << "Error reading JSON file " << filePath.toStdString() << ":\n" << jsonParseError.errorString().toStdString() << ":\n" << jsonErrorData.toStdString() << "\n" << "Please check that " << filePath.toStdString() << " is a valid .camitk JSON file";
        }
        else {
            QString errorLine(jsonData.split('\n')[lineNr - 1]);
            std::cerr << "Error reading json file " << filePath.toStdString() << ":\n" << jsonParseError.errorString().toStdString() << ":\n" << jsonErrorData.toStdString() << "\nOn line " << lineNr << ":\n" << errorLine.toStdString();
        }
        return false;
    }
    else if (!jsonDoc.isObject()) {
        std::cerr << "Error reading json file " << filePath.toStdString() << ": JSON document is not an object";
        return false;
    }
    else {
        QJsonObject allData = jsonDoc.object();

        // Access the "camitk" object
        if (!allData.contains("camitk")) {
            std::cerr << "Error reading json file " << filePath.toStdString() << ": JSON document does not contain any \"camitk\" object";
            return false;
        }

        QJsonObject camitkObj = allData["camitk"].toObject();

        if (!camitkObj.contains("extensions")) {
            std::cerr << "Error reading json file " << filePath.toStdString() << ": \"camitk\" JSON object does not contains any \"extensions\" object";
            return false;
        }
        else {
            // Transform JSON to data model
            extensions = VariantDataModel(camitkObj["extensions"].toObject().toVariantMap());

            if (!extensions.contains("actions") && !extensions.contains("components") && !extensions.contains("viewers") && !extensions.contains("libraries")) {
                std::cerr << "Error reading json file " << filePath.toStdString() << ": \"camitk\"/\"extensions\" JSON object does not contains any extensions";
                return false;
            }
            else {
                return true;
            }
        }
    }
}

// -------------------- save --------------------
bool CamiTKExtensionModel::save(const QString& filePath) {
    QFile camitkFile;
    camitkFile.setFileName(filePath);

    if (filePath.isNull()) {
        std::cerr << "Error in save(): given file path " <<  QFileInfo(camitkFile).absoluteFilePath().toStdString() << " is empty.";
        return false;
    }

    if (!camitkFile.open(QIODevice::WriteOnly | QIODevice::Text)) {
        std::cerr << "Error in save(): Could not open file " <<  QFileInfo(camitkFile).absoluteFilePath().toStdString() << " for writing.";
        return false;
    }

    QTextStream out(&camitkFile);
    out << toJSON();
    camitkFile.close();

    // now reset readExtension (to check for later modification)
    extensions.reset();

    return true;
}