/*
 * Copyright 2023 KylinSoft Co., Ltd.
 *
 * 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 3 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 implied 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/>.
 */

#include "misc.h"
#include <QDir>
#include <QFile>
#include <QJsonDocument>
#include <QDebug>

namespace utils {

Misc::Misc(QObject *parent) : QObject(parent)
{

}

bool utils::Misc::ensurePathExists(const QString &path)
{
    QDir dir(path);
    if (dir.exists(path)) {
        return true;
    }

    if (!dir.mkdir(path)) {
        qWarning() << "mkdir failed: " << path;
        return false;
    }

    return true;
}

bool Misc::ensureFileExists(const QString &fileName)
{
    QFile file(fileName);
    if (file.exists()) {
        return true;
    }

    if (!file.open(QIODevice::ReadWrite | QIODevice::Append)) {
        qWarning() << "open file failed: " << fileName;
        return false;
    }
    return true;
}

QJsonObject Misc::readJsonFromFile(const QString &fileName)
{
    QFile file(fileName);
    if (!file.open(QIODevice::ReadOnly)) {
        qWarning() << "open json file failed: " << fileName;
        return QJsonObject();
    }

    QJsonDocument jdc(QJsonDocument::fromJson(file.readAll()));
    file.close();
    return jdc.object();
}

bool Misc::writeJsonToFile(const QJsonObject &obj, const QString &fileName)
{
    QFile jsonFile(fileName);
    if (!jsonFile.open(QIODevice::WriteOnly)) {
        qWarning() << "open json file failed: " << fileName;
        return false;
    }
    QJsonDocument jdoc(obj);
    jsonFile.write(jdoc.toJson());
    jsonFile.flush();
    jsonFile.close();
    return true;
}

} // namespace utils

