Skip to content
Snippets Groups Projects
config.cpp 1.62 KiB
Newer Older
akiraohgaki's avatar
akiraohgaki committed
/**
 * A library for Qt app
 *
 * LICENSE: The GNU Lesser General Public License, version 3.0
 *
 * @author      Akira Ohgaki <akiraohgaki@gmail.com>
 * @copyright   Akira Ohgaki
 * @license     https://opensource.org/licenses/LGPL-3.0  The GNU Lesser General Public License, version 3.0
 * @link        https://github.com/akiraohgaki/qtlibs
 */

#include "config.h"

#include "file.h"
#include "dir.h"
#include "json.h"

namespace qtlibs {

akiraohgaki's avatar
akiraohgaki committed
Config::Config(const QString &configDirPath, QObject *parent)
    : QObject(parent), configDirPath_(configDirPath)
akiraohgaki's avatar
akiraohgaki committed
{}

akiraohgaki's avatar
akiraohgaki committed
Config::Config(const Config &other, QObject *parent)
    : QObject(parent)
akiraohgaki's avatar
akiraohgaki committed
{
    setConfigDirPath(other.configDirPath());
}

Config &Config::operator =(const Config &other)
{
    setConfigDirPath(other.configDirPath());
    return *this;
}

akiraohgaki's avatar
akiraohgaki committed
QString Config::configDirPath() const
{
    return configDirPath_;
}

void Config::setConfigDirPath(const QString &configDirPath)
{
    configDirPath_ = configDirPath;
}

QJsonObject Config::get(const QString &name)
{
    QString configFilePath = configDirPath() + "/" + name + ".json";
    QByteArray json = qtlibs::File(configFilePath).readData();
    if (json.isEmpty()) {
        json = QString("{}").toUtf8(); // Blank JSON data as default
    }
    return qtlibs::Json(json).toObject();
}

bool Config::set(const QString &name, const QJsonObject &object)
{
    QString configFilePath = configDirPath() + "/" + name + ".json";
    QByteArray json = qtlibs::Json(object).toJson();
    qtlibs::Dir(configDirPath()).make();
    if (qtlibs::File(configFilePath).writeData(json)) {
        return true;
    }
    return false;
}

} // namespace qtlibs