#include "CodesDirHandler.h"

#include <QDir>
#include <QDebug>
#include <QFileInfo>

#if 0
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#endif

CodesDirHandler* CodesDirHandler::instance_ = nullptr;

CodesDirHandler* CodesDirHandler::instance()
{
    if (!instance_) {
        instance_ = new CodesDirHandler();
    }
    return instance_;
}

CodesDirHandler::CodesDirHandler()
{
    if (char* homeCh = getenv("HOME")) {
        QDir d(homeCh);
        QDir dc(d.filePath(".codes_ui"));
        if (!dc.exists())
            d.mkpath(".codes_ui");

        configDir_ = dc.path().toStdString();
        qDebug() << "confDir" << configDir_.c_str();
    }

    if (char* shareDirCh = getenv("CODES_UI_DIR_SHARE")) {
        QDir d(shareDirCh);
        shareDir_ = d.path().toStdString();
        qtResourceDir_ = d.filePath("images").toStdString();
    }
    // this is for developments
    else {
        shareDir_ = "share/codes_ui/etc";
        QFileInfo fInfo(QString::fromStdString(shareDir_));
        if (!fInfo.isDir()) {
            shareDir_ = "share/metview/app-defaults";
        }
        qtResourceDir_ = shareDir_ + "/images";
    }

    qDebug() << "shareDir" << shareDir_.c_str();
    qDebug() << "qtResourceDir" << qtResourceDir_.c_str();
}

std::string CodesDirHandler::shareDirFile(const std::string& fName) const
{
    QDir d(QString::fromStdString(shareDir()));
    return d.filePath(QString::fromStdString(fName)).toStdString();
}

std::string CodesDirHandler::confDirFile(const std::string& fName) const
{
    QDir d(QString::fromStdString(configDir()));
    return d.filePath(QString::fromStdString(fName)).toStdString();
}

std::string CodesDirHandler::qtResourceDirFile(const std::string& fName) const
{
    QDir d(QString::fromStdString(qtResourceDir_));
    return d.filePath(QString::fromStdString(fName)).toStdString();
}
