#include "pqapppath.h"
#include <QCoreApplication>
#include <QFileInfo>

namespace PQ {

AppPath * AppPath::this_()
{
    static AppPath _p;
    return &_p;
}

AppPath::AppPath() : QObject(nullptr)
{
    QDir dir = QDir::temp();
    QString dirName = QString("%1.%2").arg(QCoreApplication::applicationName()).arg(QCoreApplication::applicationPid());
    if(!dir.exists(dirName)){
        dir.mkdir(dirName);
    }
    dir.cd(dirName);
    _tmpDir = dir;
    dir = QDir::home();
    dirName = ".";
    dirName += QCoreApplication::applicationName();
    if(!dir.exists(dirName)){
        dir.mkdir(dirName);
    }
    dir.cd(dirName);
    QFileInfo info(dir.absolutePath());
    setBaseDir(dir);
}

bool AppPath::setBaseDir(const QDir &dir)
{
    if(!dir.exists()) return false;
    QFileInfo info(dir.absolutePath());
    if(!info.isWritable()) return false;
    _baseDir = dir;
    if(!_baseDir.exists("config")){
        _baseDir.mkdir("config");
    }
    _configDir = QDir(_baseDir.absoluteFilePath("config"));
    if(!_baseDir.exists("cache")){
        _baseDir.mkdir("cache");
    }
    _cacheDir = QDir(_baseDir.absoluteFilePath("cache"));
    if(!_baseDir.exists("data")){
        _baseDir.mkdir("data");
    }
    _dataDir = QDir(_baseDir.absoluteFilePath("data"));

    if(!_baseDir.exists("log")){
        _baseDir.mkdir("log");
    }
    _logDir = QDir(_baseDir.absoluteFilePath("log"));
    emit pathChanged();
    return true;
}

}
