#include <app/app_version.h>

#include <QCoreApplication>
#include <QDir>
#include <QFileInfo>
#include <QSettings>
#include <QString>
#include <QUrl>

#ifdef Q_OS_MAC
#include <CoreFoundation/CoreFoundation.h>
#endif

namespace Sfdk {
namespace Constants {

static QString applicationDirPath(char *arg = nullptr)
{
    static QString dir;

    if (arg)
        dir = QFileInfo(QString::fromLocal8Bit(arg)).dir().absolutePath();

    if (QCoreApplication::instance())
        return QCoreApplication::applicationDirPath();

    return dir;
}

static QString settingsVariant(char **argv = nullptr)
{
    const QLatin1String SDK_RELEASE_FILE_PATH{"sdk-release"};
    const QLatin1String SDK_RELEASE_INFO_CONFIG_VARIANT{"SDK_CONFIG_DIR"};
    const QString applicationPath = argv ? applicationDirPath(argv[0]) : applicationDirPath();
    QString releaseFilePath = "";

    if (QCoreApplication::applicationName() == Core::Constants::IDE_CASED_ID
        || QCoreApplication::applicationName() == "sfdk"
        || QCoreApplication::applicationName() == "") {
        // Find sdk-release from qt-creator dir
#if defined(Q_OS_MAC)
        const CFURLRef appUrlRef= CFBundleCopyBundleURL(CFBundleGetMainBundle());
        const auto releaseObject = CFAutorelease(appUrlRef);
        QDir applicationDir{ QUrl::fromCFURL(appUrlRef).path() };
        applicationDir.cdUp();
        releaseFilePath = applicationDir.absolutePath() + '/' + SDK_RELEASE_FILE_PATH;
#else
        releaseFilePath = QDir::cleanPath(
            applicationPath + '/' + RELATIVE_PREFIX_PATH + '/' + SDK_RELEASE_FILE_PATH);
#endif // Q_OS_MAC
    } else {
        // Find sdk-release from tools dir
#if defined(Q_OS_MAC)
        // in MacOS tools in AuroraOS/Qt Creator.app/Contents/Resources/libexec/
        const CFURLRef appUrlRef= CFBundleCopyBundleURL(CFBundleGetMainBundle());
        const auto releaseObject = CFAutorelease(appUrlRef);
        QDir applicationDir{ QUrl::fromCFURL(appUrlRef).path() };
        applicationDir.cdUp();
        applicationDir.cdUp();
        applicationDir.cdUp();
        applicationDir.cdUp();
        releaseFilePath = applicationDir.absolutePath() + '/' + SDK_RELEASE_FILE_PATH;
#elif defined(Q_OS_WIN)
        // in Windows tools in AuroraOS/bin/
        releaseFilePath = QDir::cleanPath(
            applicationPath + "/../" + SDK_RELEASE_FILE_PATH);
#else
        // in Linux tools in AuroraOS/qtcreator/libexec/
        releaseFilePath = QDir::cleanPath(
            applicationPath + "/../../" + SDK_RELEASE_FILE_PATH);
#endif // Q_OS_MAC
    }

    const QSettings settings(releaseFilePath, QSettings::IniFormat);

    if (settings.status() == QSettings::NoError
        && settings.contains(SDK_RELEASE_INFO_CONFIG_VARIANT)) {

        return settings.value(SDK_RELEASE_INFO_CONFIG_VARIANT).toString();
    }

    return QString(Core::Constants::IDE_SETTINGSVARIANT_STR);
}

} // namespace Constants
} // namespace Sfdk
