#include "settings.h"

#include <QJsonDocument>
#include <QFile>
#include <QStandardPaths>
#include <QDir>
#include <QDebug>
#include <qjsonvalue.h>
#include <QJsonArray>


Settings::Settings() {}


QString Settings::getStateFilePath(QString &profile) {
#ifdef Q_OS_WIN
    QString stateDir = QStandardPaths::writableLocation(QStandardPaths::AppLocalDataLocation);
#else
    QString stateDir = QStandardPaths::writableLocation(QStandardPaths::StateLocation);
#endif
    QDir().mkpath(stateDir);
    return stateDir + "/settings_" + profile + ".json";
}


void Settings::saveToJson(QString profile, QString RAM, QString java_path, QString garbarge_collector_method, QJsonArray additions_list) {
    QString filePath = getStateFilePath(profile);
    QJsonObject json;
    json["RAM"] = RAM;
    json["java_path"] = java_path;
    json["garbarge_collector"] = garbarge_collector_method;
    json["additions_list"] = additions_list;

    QFile file(filePath);
    if (file.open(QIODevice::WriteOnly)) {
        file.write(QJsonDocument(json).toJson());
        file.close();
        qDebug() << "Данные сохранены в" << filePath;
    } else {
        qWarning() << "Не удалось открыть файл для записи:" << filePath;
    }
}


QJsonObject Settings::loadFromJson(QString &profile) {
    QString filePath = getStateFilePath(profile);
    QFile file(filePath);
    if (file.open(QIODevice::ReadOnly)) {
        QByteArray data = file.readAll();
        file.close();
        QJsonDocument doc = QJsonDocument::fromJson(data);
        if (doc.isObject()) {
            return doc.object();
        }
    }
    qWarning() << "Не удалось загрузить данные из файла:" << filePath;
    return QJsonObject();
}
