/*
 * Copyright 2022 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 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 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 thi1s program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */

#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()));
    return jdc.object();
}

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

} // namespace utils

