#include "pqfileutils.h"
#include <QFile>
#include "core/pqapppath.h"
#include <QJsonDocument>

namespace PQ {

bool writeAbsoluteFile(const QString & absFilePath, const QByteArray & data)
{
    QFile f(absFilePath);
    if(f.open(QFile::WriteOnly)){
        f.write(data);
        f.close();
        return true;
    }
    return false;
}

QByteArray readAbsoluteFile(const QString & absFilePath)
{
    QByteArray dt;
    QFile f(absFilePath);
    if(f.open(QFile::ReadOnly)){
        dt = f.readAll();
        f.close();
    }
    return dt;
}

bool CacheFile::writeFile(const QString & name, const QByteArray & data)
{
    return  writeAbsoluteFile(cacheFile(name),data);
}

QByteArray CacheFile::readFile(const QString & name)
{
    return readAbsoluteFile(cacheFile(name));
}

QString CacheFile::cacheFile(const QString & name)
{
    return AppPath::this_()->cacheDir().absoluteFilePath(name);
}


bool ConfigFile::writeFile(const QString & name, const QByteArray & data)
{
    return  writeAbsoluteFile(configFile(name),data);
}

QByteArray ConfigFile::readFile(const QString & name)
{
    return readAbsoluteFile(configFile(name));
}

QString ConfigFile::configFile(const QString & name)
{
    return AppPath::this_()->configDir().absoluteFilePath(name);
}

bool ConfigFile::writeObject(const QString & name, const QJsonObject & obj)
{
    auto dt = QJsonDocument(obj).toJson();
    return writeFile(name,dt);
}


QJsonObject ConfigFile::readObject(const QString & name)
{
    auto dt = readFile(name);
    return QJsonDocument::fromJson(dt).object();
}

}
